if anonymous function is defined in inner scope (e.g. within a function) this does not happen
if anonymous function is passed as an argument to a function and used in this function then this does still happen
(for normal functions this is not the case)
this does not happen for normal functions
CC @nalimilan - this is related to auto-splatting design @mbauman - maybe you know the answer immediately (or this question has been asked)
It’s simply due to using @time at global scope. Every time you write an anonymous function, Julia creates a new type (and I mean “write” literally — it’s a syntax thing). This means that repeatedly @timeing an expression that includes a newly written anonymous function will result in compilation overhead.
As you might imagine, there’s a bigger compilation overhead for broadcasting than there is for map.
julia> a = ()->nothing
#7 (generic function with 1 method)
julia> b = ()->nothing
#9 (generic function with 1 method)
julia> a === b
false
julia> typeof(a) === typeof(b)
false
So when you pass a newly written anonymous function to a function, there will be some new compilation — even if you passed the syntactically identical anonymous function before — because the newly written one has a new type.
There’s a possible future optimization that would identify syntactically identical anonymous functions to re-use the same types when possible (although perhaps just at the REPL #21113),
Note that, by the same token, you can use anonymous functions without incurring compile overhead more than once in the global scope by simply preassigning them: