简体   繁体   中英

More efficient if statement when only fired once in the game

Say I want an if statement that will only fire once each game.
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. 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.

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

...

if(CachedResult)
{
...
}

This code checks to see if 'cachedResult' is null. If it is, than it run the ComplicatedCalculation() method to get the result. After that 'cachedResult' is populated and the if statement won't rerun the calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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