Happy new year to all.
I have a quick question about writing effcient looping code. To describe a problem, let me use a simple for looping statement which check if a number is even and store that number into an array (result_arr) if it is even. This is just for example.
I can consider two options: Option 1 and Option 2, see below. Option 1 is always faster than Option 2. It seems because Option 2 creates an extra array from [ … ] operation: 7.13% gc_time. But, I would like to write Option 2 since it is simple one line and easy to read.
Could there be any simple and efficeint Julia code, as simple as Option 2 and as fast as Option 1?
Thank you very much in advance.
result_arr = Array{Float64,1}(undef,10^8)
Option 1
@time begin
for i in 1:10^8
iseven(i) ? result_arr[i] = i : result_arr[i] = 0;
end
end
Option 2
@time [iseven(i) ? result_arr[i] = i : result_arr[i] = 0 for i=1:10^8]
output>
2.463796 seconds (150.00 M allocations: 2.235 GiB, 3.99% gc time)
3.201820 seconds (150.05 M allocations: 2.983 GiB, 7.13% gc time)