C#

What surprises can C# properties hide?

Posted by Strainu on May 10, 2007
C# / 1 Comment

One of my colleagues was recently working on an app that was supposed to transform a color bitmap into a black and white image. The image was quite large (1600×1024) and the algorithm quite simple (2 nested for’s were used to go through the image).

He had implemented this algorithm before, but with a small difference. Can you tell what the difference is?

public Bitmap Grayscale1(Bitmap srcImg)
{
...
// get source image size
int width = srcImg.Width;
int height = srcImg.Height;
// for each line
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, src += 3)// for each pixel
{
src[0] = src[1] = src[2] = (byte)(0.2125 * src[2] + 0.7154 * src[1] + 0.0721 * src[0]);
}
...
}
...
return srcImg;
}
public Bitmap Grayscale2(Bitmap srcImg)
{
...
// for each line
for (int y = 0; y < srcImg.Height; y++)
{
for (int x = 0; x < srcImg.Width; x++, src += 3)// for each pixel
{
src[0] = src[1] = src[2] = (byte)(0.2125 * src[2] + 0.7154 * src[1] + 0.0721 * src[0]);
}
...
}
...
return srcImg;
}

The answer: the second program was running much more slowly than the first. (almost 5 times slower, actually) 🙂

At first glance, the programs do the same thing. However, Grayscale1 was using two local variable, width and height to keep the size of the image. At each iteration, instead of calling the Height and Width properties of the image, the program was using the local variables.

So why was this causing such a dramatic effect on the running time? My friend’s idea was that the local variables were kept by the program in the registries, thus allowing for a quicker access time than the properties, which are in fact functions.

However, another programmer decided to do a little bit of profiling on the program and discovered something much more interesting: the getHeight() and getWidth() functions (corresponding to the Height and Width properties of the image) were not just returning a variable, as one might expect, but were actually calling some GDI+ functions.

You can read the original story and the follow-up (both in Romanian). And just in case you haven’t found out just yet, you COULD hit the same problem in C++ (Microsoft C++, that is).

Share and Enjoy:
  • Facebook
  • Twitter
  • Identi.ca
  • LinkedIn
  • Reddit
  • Add to favorites