We as a community should be more understanding of Julia's flaws

No, it isn’t:

julia> function f!(result_array)
           for k in eachindex(result_array)
               value = sin(k)
               result_array[k] = value
           end
       end

f! (generic function with 1 method)

julia> result_array = zeros(10^6);

julia> @btime f!($result_array);
  11.649 ms (0 allocations: 0 bytes)

The situations in which “it should do something” but it is not doing it are, for instance, like this:

julia> function f!(result_array)
           for k in eachindex(result_array)
               value = [sin(k), cos(k)]
               result_array[k] .= value
           end
       end
f! (generic function with 1 method)

julia> result_array = [ zeros(2) for _ in 1:10^6 ];

julia> @btime f!($result_array);
  41.204 ms (1000000 allocations: 76.29 MiB)

The compiler should (and it will soon :crossed_fingers:) recognize that the intermediate vector [sin(k), cos(k)] does not escape the scope of the (iteration of) the loop, and thus should be stack allocated, or completely eliminated ( to read here result_array[k] .= (sin(k), cos(k)), which is non-allocating then).

7 Likes