Search code examples
for-looprustvariable-assignment

Which is more efficient: assigning every time or checking?


Say that you have a variable ididit: mut bool which controls whether or not something has been done, and a loop in which that thing may be done. For visualization purposes, here's some example code:

let mut ididit: bool = false;

for i in 0..SomeArbitraryValue {
    // do stuff
    if (conditions) {  // While certainly possible, this probably won't run every iteration.
        ididit = true;
    }
}

With that in mind, would it be more efficient to check whether or not ididit is already true before assigning?

In other words, which is more efficient: checking for redundancy or just assigning every time?


Solution

  • So much depends on the context. For your trivial example, Sven is correct in saying that it likely gets optimized to an assignment. But if it doesn't, you are costing an extra memory cycle for the check. And even if it does get optimized out, it still adds code complexity that has to be maintained. If you are dealing with more complex entities it can be quite different.

    Consider a case where reading a value is delayed while other processing is going on, e.g. a web access that is synchronous because the value is usually needed to continue, and writes just get put in a queue while execution continues. Now the checking gets expensive and it is better to write without checking.

    Now consider the situation where writing to an object makes it "dirty" and forces other processing. An example is having the value tied to a displayed object. Assigning to that value gets quite expensive since it involves a display update while reading it does not. The display update is asynchronous so it may not be noticed using metrics but it can affect the application as a whole. So in this case checking could be much better. This is one situation where it takes some real thought.

    Most of the time you can know which is better by thinking it through while taking the context into account. But if you have to run metrics to determine which is which, it usually ends up being so little difference as not to matter enough to incur the code complexity cost. You can end up over-optimizing your app into an unmaintainable mess.