Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the c# compiler optimizes Count properties?

List<int> list = ...

for(int i = 0; i < list.Count; ++i)
{
           ...
}

So does the compiler know the list.Count does not have to be called each iteration?

like image 632
Vitaliy Avatar asked Jul 20 '10 21:07

Vitaliy


People also ask

Which is positive C or T?

One coloured line should be in the control line region (C), and another coloured line should be in the test line region (T). Two lines, one next to C and one next to T, even faint lines, show the test is positive.

What means C and T?

Reading the results "If you see a test line, it means that there are the viral nuclear protein antigens in your specimen, which is supposed to be interpreted as a positive test result," he said. A positive result: Two lines on control (C) and test (T). Negative: One line on control (C).

What does the C and T mean on the lateral flow test?

Negative result: one line next to C shows the test is negative. Positive result: two lines, one next to C and one next to T, even faint lines, shows the test is positive. Positive test results need to be reported to the NHS, and the school will help guide you here.

Is C or T positive on Covid test?

For most positive tests, a reddish-purple line will appear in the Control (C) Zone and the Test (T) Zone; however, in cases where the viral load in the sample is very high, the line in the Control (C) Zone may not be present or may be very faint.


1 Answers

Are you sure about that?

List<int> list = new List<int> { 0 };

for (int i = 0; i < list.Count; ++i)
{
    if (i < 100)
    {
        list.Add(i + 1);
    }
}

If the compiler cached the Count property above, the contents of list would be 0 and 1. If it did not, the contents would be the integers from 0 to 100.

Now, that might seem like a contrived example to you; but what about this one?

List<int> list = new List<int>();

int i = 0;
while (list.Count <= 100)
{
    list.Add(i++);
}

It may seem as if these two code snippets are completely different, but that's only because of the way we tend to think about for loops versus while loops. In either case, the value of a variable is checked on every iteration. And in either case, that value very well could change.

Typically it's not safe to assume the compiler optimizes something when the behavior between "optimized" and "non-optimized" versions of the same code is actually different.

like image 164
Dan Tao Avatar answered Sep 30 '22 16:09

Dan Tao