The impact of different ways of passing parameters on the speed of function computation

You need to interpolate global variables, since otherwise global variables are slow:

julia> @btime f1(a, b); # non-interpolated globals
  15.406 ns (1 allocation: 16 bytes)

julia> @btime f1($1.0,$2.0);
  1.958 ns (0 allocations: 0 bytes)

julia> @btime f1($a, $b);
  1.959 ns (0 allocations: 0 bytes)

This is an artifact of benchmarking in global scope. When you actually use a function like f1(a,b) in practice, it will presumably be inside a function if you care about performance, in which case there is no issue with global variables.

With arguments taken from an array, you still need to interpolate for benchmarking if it is a global array:

julia> @btime f1(c[1],c[2]);   # non-interpolated global array = slow
  59.596 ns (3 allocations: 48 bytes)

julia> @btime f1($c[1],$c[2]);
  2.375 ns (0 allocations: 0 bytes)

but, even when the array c is interpolated (removing the global-variable penalty), there is still a tiny bit of time required to fetch the elements from an array.

As @GunnarFarneback pointed out above, with constant arguments f1(1.0,2.0) may be faster because when the arguments are constants the compiler can sometimes inline the whole function and evaluate it (to 24.0 in this case) at compile time, which is why f1(1.0,2.0) is a bit faster still:

julia> @btime f1(1.0,2.0);
  1.125 ns (0 allocations: 0 bytes)
2 Likes