I've found this problem and corrected it. I came and wanted to post it and
"Jon Skeet [C# MVP]" <skeet@pobox.com> wrote in message
news:MPG.1e37facedc3984e798cd0a@msnews.microsoft.com...
> Amos Zhang <amoszh@gmail.com> wrote:
>> I am totally confused...
>>
>> Just now, I changed the loop control block in my code from
>>
>> (1)
>> for (int y=0;y<Height;y++)
>> for (int x=0;x<Width;x++)
>> {}
>>
>> to
>>
>> (2)
>> for (int y = Height - 1; y >= 0; y--)
>> for (int x = Width - 1; x >= 0; x--)
>> {}
>>
>> the performance goes back to normal..., the same as what I got on VS.NET
>> 2003
>>
>> I changed the loop control back to (1), and the performance dropped
>> again!
>>
>> I know that when two numbers A and B are compared, say, A>B, the actual
>> operation is :
>>
>> C=A-B;
>> return C>0;
>>
>> does the substract operation in the first comparison of the loop cost so
>> much in performance?
>
> No - I suspect the problem is in the Height and Width properties.
> They're evaluated on every iteration of the loop in the first case, but
> only once in the second case. Normally that's not a problem - if the
> properties are backed by simple variables, the JIT inlines the access
> and you don't lose any performance. (Indeed, for arrays you can *gain*
> performance, because the JIT notices that you're making sure that the
> loop counter is less than Length and can eliminate range checks.)
>
> In this case, my guess is that the Height and Width properties have
> become more expensive to calculate. To test this, cache them first:
>
> int height = Height;
> int width = width;
>
> for (int y=0; y < height; y++)
> {
> for (int x = 0; x < width; x++)
> {
> ...
> }
> }
>
> If that gives the same performance as your second code, I'd use that
> with a comment above the variable declarations to explain why you're
> doing it. I find it easier to understand a loop which is going
> "forwards" :)
>
> --
> Jon Skeet - <skeet@pobox.com>
>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet > If replying to the group, please do not mail me too