Ryder
Ryder

Reputation: 351

Accessing Object properties in a loop

Is it better to assign a object property to a variable first instead of using it directly in a loop?

Say I have a bitmap Bitmap img = new Bitmap("image.jpg") and I needed to loop through all the pixels to do some processing. For a 1080p image that's about 2 million pixels. Does it matter if I use data.Stride or assign them to a variable first int dataStride = data.Stride? I need to access it each time to calculate the offset but the dataStride is a constant of the image.

data = editImage.LockBits(new Rectangle(0, 0, editWidth, editHeight), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
byte* dataPtr = (byte*)data.Scan0;
dataStride = data.Stride;

I assign them to a variable first since I am thinking that it has to access the object (each time) first and then access the integer from the object (each time) which is slower. And since it is a large loop... it adds up. So assigning the property to a variable first will be faster since it can access the int value directly. Is this correct?

Upvotes: 3

Views: 238

Answers (1)

Nathan Wiebe
Nathan Wiebe

Reputation: 802

Yes. No matter how simple the property, accessing it still has the overhead of a function call. A variable is faster, especially if you are doing something 2 million times.

Upvotes: 2

Related Questions