fleico
fleico

Reputation: 146

For loop inside vs outside function

I've been experimenting with this for a while but can't seem to come to a conclusion. If I have the following options,

function fxn1()
    for i in 1:N
        do_something()
    end
end

function main()
    fxn1()
end

and

function fxn2()
    do_something()
end

function main()
    for i in 1:N
        fxn2()
    end
end

Is there a general consensus on which one is preferred? I have been playing around with @time, and have been getting mixed results.

What surprised me were the instances when the second option was faster, since I would expect the extra subroutine/function calls to make the code a bit more expensive. I paid attention to memory allocations, which were nearly the same for both cases for each of the experiments I did, and even then the lesser wasn't necessarily the faster.

Thanks in advance for any input!

Upvotes: 1

Views: 312

Answers (1)

Michael K. Borregaard
Michael K. Borregaard

Reputation: 8044

So, it's hard to answer given the MWE. I mean why would you even have function fxn2()? But to say something general, in Julia you generally prefer defining a function on a single element, then iterate across that element to apply it. This plays nicely with the broadcasting semantics of julia (see eg https://docs.julialang.org/en/v1/manual/functions/#man-vectorized-1)

So as an example, if you want to take the sine of an array of numbers in Julia, you would do y = sin.(x) which is the same as

y = Vector{Float64}(undef, length(x))
for i in eachindex(x)
   y[i] = sin(x[i])
end

Upvotes: 3

Related Questions