Creating lots of anonymous functions in a loop

#1

This is probably a silly question, but…

I often have a code pattern like the following:

for n = 1:something_large
    anon_func = x -> some_func(x, n)  #Example anon func that needs to be defined within loop
    i = findfirst(anon_func, A)
    # some other code
end

Will a code pattern like this be creating a huge number of anonymous functions, and if so, are there any implications to this? Or will it create only one anonymous function at the code lowering point, and so there is basically nothing to worry about here? Any other potential pitfalls I should be aware of?

Cheers and thanks to all responders,

Colin

0 Likes

#2

It create only one version of the lowered code.

0 Likes

#3

Yup, pretty much that. Each closure created in the loop will be a different instance of the same type, and compilation will only need to happen once. The only potential performance issue is https://github.com/JuliaLang/julia/issues/15276 The symptom to look for there is Core.Box in your @code_warntype

1 Like

#4

Great! Thanks for responding.

0 Likes

#5

Ah! I’d seen the word “closure” pop up quite a lot around here but never quite worked out what it meant. The comments on that issue make things much clearer. Thanks for posting.

Cheers,

Colin

0 Likes