Creating lots of anonymous functions in a loop

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

1 Like

It create only one version of the lowered code.

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 performance of captured variables in closures · Issue #15276 · JuliaLang/julia · GitHub The symptom to look for there is Core.Box in your @code_warntype

1 Like

Great! Thanks for responding.

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