Question

In C#, suppose I have a foreach loop and it is possible that the iterator will be empty. Following the loop, more actions need to be taken only if the iterator was not empty. So I declare bool res = false; before the loop. Is it faster to just set res = true; in each loop iteration, or to test if it's been done yet, as in if (!res) res = true;. I suppose the question could more succinctly be stated as "is it faster to set a bool's value or test its value?"

In addition, even if one is slightly faster than the other, is it feasible to have so many iterations in the loop that the impact on performance is not negligible?

Was it helpful?

Solution

To kill a few minutes:

static void Main(string[] args)
    {
        bool test = false;

        Stopwatch sw = new Stopwatch();
        sw.Start();

        for (long i = 0; i < 100000000; i++)
        {
            if (!test)
                test = true;
        }

        sw.Stop();


        Console.WriteLine(sw.ElapsedMilliseconds + ". Hi, I'm just using test  somehow:" + test);
        sw.Reset();
        bool test2 = false;
        sw.Start();

        for (long i = 0; i < 100000000; i++)
        {
                test2 = true;
        }

        sw.Stop();

        Console.WriteLine(sw.ElapsedMilliseconds + ". Hi, I'm just using test2 somehow:" + test2);
        Console.ReadKey();
    }

Output:
448
379

So, unless missed somthing, just setting the value is faster than checking and then setting it. Is that what you wanted to test?

EDIT:

Fixed an error pointed out in the comments. As a side note, I indeed ran this test a few times and even when the miliseconds changed, the second case was always slighty faster.

OTHER TIPS

if (!res) res = true is redundant.

The compiler should be smart enough to know that res will always end up being true and remove your if statement and/or completely remove the set altogether if you compile with Release / Optimize Code.


To your question itself. It should be faster to set a primitive value than to actually compare and set. I highly doubt you would be able to accurately measure the time difference at all on a primitive and just thinking about this alone consumed more time than the process will in x exagerrated iterations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top