Access to object properties in a loop

Is it better to first assign the property of an object to a variable rather than use it directly in a loop?

Say I have a bitmap Bitmap img = new Bitmap("image.jpg")and I had to iterate over all the pixels in order to do some processing. For a 1080p image, this is about 2 million pixels. Does it matter if I use data.Strideor assign them to a variable first int dataStride = data.Stride? I need to access it every time to calculate the offset, but the dataStride is an image constant.

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

I first assign them to a variable, since I think that it must first access the object (each time), and then access the integer from the object (each time), which is slower. And since this is a big cycle ... it develops. Therefore, assigning a property to a variable will be faster at first, since it can directly access the int value. Is it correct?

+3
source share
1 answer

Yes. No matter how simple the property, access to which still has the overhead of calling the function. A variable is faster, especially if you do something 2 million times.

+2
source

All Articles