Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested functions performance (F#)

Are there any performance issues with nested functions in F#?

If I have a function which is called on every item in an array, and this function has nested inner functions, does that mean on every iteration it needs to declare, create and assign all the inner nested functions?

Seems awfully inefficient but I really like the readability of nested functions as opposed to private outer functions.

like image 901
Connel Avatar asked Dec 24 '16 11:12

Connel


1 Answers

Nested functions are extracted by the compiler into classes that inherit from FSharpFunc, nested within the module or type where their parent function is defined in. So the compiler essentially does for you what you would otherwise do by hand, with outer private functions.

All that happens at runtime is instantiation of these objects. There is a cost to it compared to executing inline code, but I suppose drastically less than what you anticipated in your mental model.

It does leave you with an extra object to GC though. Would this object instantiation matter in a tight loop then? In a naive implementation, where the function object is instantiated anew in each iteration, perhaps yes. But F# compiler is smarter than that and typically instantiates the functions used in the body of the loop once, outside the loop. So again, the cost is probably as low as it can be.

When in serious doubt, consult ILSpy and benchmark. As a rule of thumb - don't fret over it and just use nested functions.

like image 75
scrwtp Avatar answered Sep 28 '22 00:09

scrwtp