I think you are encouraged to use these kind of for
loops in Julia:
b = [i+1 for i in [1,2,3]]
but I wonder why, apart from more compact syntax which leads to better readability. Are these inline for loops more efficient to evaluate expressions? If yes, why?
These for
loops are called array comprehensions. They are a simple notation for a common programming pattern of allocating an array and then filling each element with a value based on some calculation.
Doing this without a comprehension is possible and probably about as fast if done correctly (removing unnecessary bounds checks with @inbounds). For the example in the question, the following code does the same:
let tmp = [1,2,3], len = length(tmp)
b = Vector{Int}(len)
@inbounds for (n,i) in enumerate(tmp)
b[n] = i+1
end
b
end
In most cases using the form in the question is a win for both performance and readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With