Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline for loops in Julia

Tags:

for-loop

julia

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?

like image 867
rivendell Avatar asked Oct 14 '17 19:10

rivendell


1 Answers

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.

like image 186
Dan Getz Avatar answered Sep 30 '22 04:09

Dan Getz