gleb.kudr
gleb.kudr

Reputation: 1508

Caching function result on c#

Let us have this kind of code:

 Function<int,int> someFunc=(x)=>{
 //SomeCalc
 return y;
 }

than I want to use my function that way:

 int result;
 if(someFunc(k)!=0)
 {
 result=someFunc(k);
 }

The question is does the compiler caches the function result so it will be calculated only one time? Or it will be calculated two times? Tried to google the answer but with no luck.

And what about caching the closures?

Upvotes: 0

Views: 504

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500675

The C# compiler does no caching of the results here. I wouldn't expect the JIT to in general, either. You can do it yourself on a local basis very easily of course, just by using a local variable. You could also write a little memoization method to apply to the closure itself, so that the results were cached more globally - but you'd need to be careful about how you used that.

The C# compiler can cache the lambda expression itself in certain circumstances, but it's an implementation detail. In particular, I believe that any lambda expressions which don't capture any variables (including this) are cached by the Microsoft implementation.

Upvotes: 1

Pavel
Pavel

Reputation: 910

The result is not cached. The calculation will be performed each time you call the delegate.

Upvotes: 0

Servy
Servy

Reputation: 203824

The function will be executed twice. There is no way for the compiler/runtime to know if the result of the function will be the same the second time. You would need to cache the value yourself if that was the desired functionality of the function.

In this case though you're better off just storing the result of the function as a variable so that you can validate it and then use it, rather than having the function cache all results it generates.

The use of lambdas, closures, etc. doesn't change any of the above statements.

Upvotes: 2

Related Questions