For loop with variable range so slow

Yet another option is to make the global variable typed:

julia> n_T::Int = 100 # assign type!
100

julia> for i = 1:2
                  @time begin
                      n = 1
                      for j = 1:n_T
                          n += j
                      end
                  end
              end
  0.000000 seconds
  0.000000 seconds

You can subsequently assign another integer to n_T and it’ll remain fast.

As discussed here (Why is there a performance difference between global and local variables in non-interactive Julia programs?):

A global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables. Variables should be local, or passed as arguments to functions, whenever possible.

However, if you fix the type (like n_T::Int = 100), this is no longer a problem. This was introduced in Julia 1.8 (Types · The Julia Language):

As of Julia 1.8, type declarations can now be used in global scope i.e. type annotations can be added to global variables to make accessing them type stable.

4 Likes