简体   繁体   English

如果仅在游戏中触发一次语句,则效率更高

[英]More efficient if statement when only fired once in the game

Say I want an if statement that will only fire once each game. 假设我想要一个if语句,它只会在每个游戏中触发一次。
It seems like a waste of effort for me to let the cpu ever check the validity of that condition again once this has happened. 一旦发生这种情况,让CPU重新检查该条件的有效性对我来说似乎是浪费时间。 Is there a way to somehow not have this checking ever again? 有办法以某种方式不再进行此检查吗? It mind not result in any significant performance gain at all. 它介意根本不会导致任何显着的性能提升。 But I'm just curious. 但是我很好奇。

I would like a generic solution that's why I keep it so vague, because I run in these kinds of situations quite often. 我想要一个通用的解决方案,这就是为什么我让它含糊不清,因为我经常在这种情况下运行。

Pseudocode: 伪代码:

if(CoinCollected && !CoinCollectedBefore)
{
  //Do stuff   
}

Depending on what needs to check for that if condition the usual solution is to create a private bool and then check it if already set. 根据需要检查的条件,通常的解决方案是创建一个私有bool,然后检查是否已设置。

private bool cachedResult;
protected bool CachedResult
{
    get { return cachedResult ?? (cachedResult = ComplicatedCalculation()); }
}

...

if(CachedResult)
{
...
}

This code checks to see if 'cachedResult' is null. 此代码检查'cachedResult'是否为null。 If it is, than it run the ComplicatedCalculation() method to get the result. 如果是这样,则运行ComplicatedCalculation()方法以获取结果。 After that 'cachedResult' is populated and the if statement won't rerun the calculation. 之后,将填充“ cachedResult”,并且if语句将不会重新运行计算。

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

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