Efficient looping statement in Julia

It is a bit unfair to put @inbounds in one of the functions and not the other though.

julia> function option3_inb!(a)
           foreach(1:length(a)) do i
               @inbounds a[i] = iseven(i) ? 1 : 0
           end
       end;

julia> # option3_inb!(a) = foreach(i -> (@inbounds a[i] = iseven(i) ? i : 0), 1:length(a)) # same as above

julia> @btime option3!($a);
  695.627 μs (1 allocation: 16 bytes)

julia> @btime option4!($a);
  359.022 μs (0 allocations: 0 bytes)

julia> @btime option3_inb!($a);
  359.901 μs (1 allocation: 16 bytes)

While “you don’t generally optimize Julia code by digging through the language or standard library to find the best “built-in” construct” is true, there is also no need to write C-style code as soon as you want something to be fast. Using higher level functions can make the code simpler to read and should in most cases come with little to no overhead.

1 Like