Type stability and assignments of functions

I’m trying to understand how assigning a function to another variable affects type stability. Consider the following example:

f(x) = x     # any function
g = f
ff(x) = f(x)
gg(x) = g(x)

Then

@code_warntype f(1)    # good
@code_warntype g(1)    # good
@code_warntype ff(1)   # good
@code_warntype gg(1)   # bad

More precisely, for gg I get

Body::Any
1 ─ %1 = Main.g(x)::Any

In the application I have in mind, f would be a closure returned by some function, and g is the name I give to it early on in my code. Then using g in other functions like gg would lead to performance problems. Is there a way around this?

1 Like

This is slightly tricky. Defining a function like this implicitly makes f a const (when at global scope). Using const globals is totally fine for performance.

This assignment creates a new non-const variable named g with the same value as f. Your use of g within gg thus constitutes the use of a non-constant global variable, which is why type inference fails.

In global scope, you can do:

const g = f

In local scope (e.g. inside a function), you don’t need to worry about this at all.

5 Likes

Great, thanks!