简体   繁体   English

c#上的缓存函数结果

[英]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? 那么关闭缓存呢?

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. lambda,闭包等的使用不会改变上述任何陈述。

The C# compiler does no caching of the results here. C#编译器不会在此处缓存结果。 I wouldn't expect the JIT to in general, either. 我也不希望JIT一般。 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. 您还可以编写一个小的memoization方法来应用于闭包本身,以便结果更全局地缓存 - 但是您需要注意如何使用它。

The C# compiler can cache the lambda expression itself in certain circumstances, but it's an implementation detail. C#编译器可以在某些情况下缓存lambda表达式本身,但它是一个实现细节。 In particular, I believe that any lambda expressions which don't capture any variables (including this ) are cached by the Microsoft implementation. 特别是,我相信任何不捕获任何变量(包括this )的lambda表达式都由Microsoft实现缓存。

The result is not cached. 结果未缓存。 The calculation will be performed each time you call the delegate. 每次调用代理时都会执行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM