I prefer the struct-based strategy because:
-
For each typeI was wrong about this, see @rdeits answer below. If the closures come all from the same factory (i.e., outer function) they will have the same type for the same type of captured variables (if the compiler infer the types right, see the second point). So, for the examples above it would be the same. TheTyou use there will be one type ofAdder{T}. The function factory strategy will create different closures (each with a different type) each time you run it, even with the same value. It seems to me, therefore, that the function factory strategy overspecializes.structapproach can give you a finer control over specialization, as you can decide how much you want to parametrize thestructtype over the captured variables, and you know the type is the same being built inside any function. - There are some performance problems with closures, while I am not sure if they would affect your specific case: https://github.com/JuliaLang/julia/issues/15276#issuecomment-628844489 Basically, closures often lose type information of captured bindings and end up boxing them unnecessarily.
- You can use a
mutable structto change the boxed value if you need it, and if you do not then you can use an immutablestructwhich (I think) it ismore lightweight than a closureEDIT: seems like they are about the same, as closures lower to anonymous immutable structs.