Localizing variables: performance implications?

Is there any advantage to localizing variables in a Julia function?
As an example, suppose that MyStruct is a mutable struct with a field x:

mutable struct MyStruct
     x0
     # ...
end

and a function which takes an instance of MyStruct as an argument:

function foo(z::MyStruct)
    #... use z.x0 many times ...
end

Is it recommended to “localize” x0 in foo as a constant, as

function foo(z::MyStruct)
    const x00 = z.x0
    #... use x00 many times ...
end

?

1 Like

There’s no advantage and not current allowed to make a variable constant. The compiler doesn’t need that information at all.

There can be an advantage to just do x00 = z.x0. It may or may not be possible for the compiler to infer that. The effect of that can range from improving the performance by a order of magnitude (e.g. when that helps alias analysis to enable loop vectorization) to slightly negative (e.g. when the increase in register pressure cause additional spilling)

5 Likes

You mean that the compiler deduces the ‘constantness’ of a variable automatically in any case, or only if one makes an explicit assignment like x00 = z.x0?

I’m not sure how you make a var without an assignment

Sorry, I don’t get your question :roll_eyes:
I just need more clarification on your original answer; it’s rather terse and technical.

@yuyichao said that it depends, so best just profile it. :wink:

I did not say “it depends” for constantness. I just don’t know what is the difference between a variable (automatically) in any case and an explicit assignment like x00 = z.x0

Sorry!