I loved the idea used in the accepted answer here. My understanding of it is that it is an elegant way of using an interface as a method parameter without having to implement the interface. SRTP is used for duck typing to adopt a type (excuse the OO term, happy to learn the FP one) to the interface:
let inline namedModel< ^T when ^T : (member Name : string)> (model:^T)=
{ new INamed with
member x.Name =
(^T : (member Name : string) model) }
What confuses me in the code above which I took from the accepted answer is the runtime behaviour of the inlined method.
It appears to me that this method will create and return a new implementation of the INamed every single time it is called. As I asked in the comments in the linked question, would not this lead to a lot of pressure on the garbage collector if namedModel
method was called many times?
I'm really keen to use this approach but I cannot dare go ahead with lest my understanding of its memory consumption is correct.
Yes, it will create a new object on every call.
But keep in mind the first rule of optimization: first measure, then optimize. Are you sure that creating an object on every call would be prohibitively expensive in your case? Have you measured?
Another thing to keep in mind is that in normal code you are constantly creating and discarding objects, often without even thinking of it. The .NET garbage collector is specifically designed to handle this.