Recently I made an image questionProgramTo traverse a large image, extract the information of each pixel and use bitmap and bitmapdata. Because the image size is very large (2000*1000), it takes a long time for each operation. It takes more than 12 seconds to complete the operation,CodeIt has been optimized many times, and there has never been a qualitative change. Today, with a try, we will extract all the object attribute access in the loop out of the loop, and the speed will go up, the expression capability is limited. Here we can look at the Code directly:
Not optimized
Public Void Binary ()
{
For ( Int J = 0 ; J < Originalimage. height; j ++ )
{
For ( Int I = 0 ; I < Originalimage. width; I ++ )
{
Brightness = Imagebrightness [I + J * Originalimage. Width];
If (Brightness < 128 )
{
Binaryimagedata [I + J * Originalimage. Width] = 1 ;
}
Else
{
Binaryimagedata [I + J * Originalimage. Width] = 0 ;
}
}
}
}
In the above Code, the object attributes such as originalimage. width are accessed every time in the loop. Now we will refer it to the out-of-Loop
Optimized Code
Public Void Binary ()
{
Int H = Originalimage. height;
Int W = Originalimage. width;
For ( Int J = 0 ; J < H; j ++ )
{
For ( Int I = 0 ; I < W; I ++ )
{
Brightness = Imagebrightness [I + J * W];
If (Brightness < 128 )
{
Binaryimagedata [I + J * W] = 1 ;
}
Else
{
Binaryimagedata [I + J * W] = 0 ;
}
}
}
}
It is to use a simple variable to replace the property of the object in a loop. After testing, the speed of my program has been improved by more than 20 times after optimization, traversing a 3000*2000 graph reduces from nearly 40 seconds to 1500 milliseconds, with remarkable results.
There are two possible reasons for inefficient access to attributes through simple analysis.
1. Other operations must be performed inside the get attribute, which takes up time
2. To take the attribute of an object and locate the object (I do not know how to describe it, it may be called addressing more accurately), this part of time is increasing through the accumulative effect of loops.
The above is just a personal guess. You are welcome to help me analyze the exact cause.