Is it faster to set a variable every frame or check if it needs to be changed?

I’m working on the controls for my HUD, and trying to figure out the most efficient way to manage menu activations. The simplest solution would obviously to be to make a bool indicating whether each menu was supposed to be enabled, then run a check against them every frame as such:

public bool menuEnabled = false;

public void UpdateMenuScreen(){
	MenuScreen.SetActive (menuEnabled);
}

This is a pretty simple operation, but since it will be executing every frame (to ensure the UI updates as you use it) I want to ensure that it’s fairly optimal. To that end, is it faster to simply run SetActive once per frame, per menu, or to check each frame if one the menu bools has changed, and call SetActive if and only if its enabled status has changed?

If it causes you to worry about performance, use events instead: http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx

That way you will be able to subscribe things to various places for them to respond on state change(close button, esc key etc)

Generally, it is a bad practice to do something useless every frame, but if optimization will cost maintainability it is better to pay with performance instead. In C# property access may involve mutators which might trigger validations, object state changes and so on. Every case requires profiling. There is no correct answer which solution will be faster to every particular case.

While it is true that you shouldn’t do anything every frame unless you need to, the actual answer to your question is that it is faster to set the variable.

In both cases, you are likely to miss cache when retrieving the variable, and the cache miss will tend to dominate the performance. However, if you test the variable, you will also branch. Usually (presuming the variable normally stays the same) branch prediction will save you from the perf hit, but when the value changes, you will incur a branch penalty. Dirtying the cache by changing the variable has no performance penalties that I’m aware of. However, it may be possible to saturate the cache - core pipe with dirty caches.

In this particular situation, the correct code is:

public bool menuEnabled {
  set {
    MenuScreen.SetActive(value);
  }
}

And nothing else.

Stopwatch
You can see how long the execution takes.