Running the following function with a 2D array is much slower than running it with the same array but flattened to a 1D array, and both return the same result. Why is the 2D version slower?
function test(data::Array{Float64}; iterations::Int = 100)
output = copy(data)
iteration = 0
while iteration < iterations
iteration += 1
for i in eachindex(output)
next = nextfloat(output[i])
if next < 0.5
output[i] = next
end
end
end
return output
end
which can be compared like this
arr_2D = rand(Float64, 1000, 1000);
arr_1D = arr_2D[:]; # flat 1000 * 1000
@time test(arr_1D, iterations = 200); # fast, e.g. 0.2 seconds
@time test(arr_2D, iterations = 200); # slow, e.g. 1.3 seconds
test(arr_1D, iterations = 200) == test(arr_2D, iterations = 200)[:] # true
julia> @time test(arr_1D, iterations = 200); # fast, e.g. 0.2 seconds
0.198706 seconds (8.83 k allocations: 8.078 MiB, 9.40% gc time, 12.31% compilation time: 100% of which was recompilation)
julia> @time test(arr_2D, iterations = 200); # slow, e.g. 1.3 seconds
1.237346 seconds (11.62 k allocations: 8.216 MiB, 1.40% compilation time: 100% of which was recompilation)
julia> test(arr_1D, iterations = 200) == test(arr_2D, iterations = 200)[:] # true
true
julia> @time test(arr_1D, iterations = 200); # fast, e.g. 0.2 seconds
0.160560 seconds (3 allocations: 7.629 MiB, 2.95% gc time)
julia> @time test(arr_2D, iterations = 200); # slow, e.g. 1.3 seconds
1.207420 seconds (3 allocations: 7.629 MiB)
I am unable to determine if this performance difference is only related to the use of 1D vs 2D array, the use of nextfloat
, or a combination of both.