Groups | Blog | Home
all groups > dotnet performance > january 2006 >

dotnet performance : Significant performance dropping of unsafe code in VS.NET 2005 Pro


Amos Zhang
1/16/2006 9:20:59 PM
Hi all,

Yesterday I got a copy of VS.NET 2005 from our department and tried it. Part
of my project code is to read/write images to/from a byte array with unsafe
code (which I found in MSDN knowledge base). The code ran well on VS.NET
2003, but the performance significantly dropped on 2005 pro. I make the
guess that the performance problem is related to unsafe code because other
parts run normally.

Does anybody else meet the same problem and have any idea how to improve the
performance?

Thanks

Amos

Amos Zhang
1/17/2006 9:11:58 PM
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?

Amos


[quoted text, click to view]

Jon Skeet [C# MVP]
1/18/2006 7:12:50 AM
[quoted text, click to view]

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
Amos Zhang
1/24/2006 8:39:52 AM
You are great, man!

I've found this problem and corrected it. I came and wanted to post it and
found you've done it!

Thanks for the reply, anyway

Amos

[quoted text, click to view]

AddThis Social Bookmark Button