Efficient use of C/C ++ Variables
1. efficiency issues due to variable types
In addition, subtraction, and multiplication operations, the efficiency of integer operations is significantly higher than that of floating-point and double-precision operations. Therefore, in the cycle, integer operations are used to replace floating-point and double-precision operations, it will improve the program efficiency.
Example:
Double precision calculation:
Double S = 2.5;
For (INT I = 0; I <100; I ++)
{
S * = 3;
}
The operation after converting to an integer:
Int S1 = 25;
Double S2;
For (INT I = 0; I <100; I ++)
{
S1 * = 3;
}
S2. = S1/10.0;
2. efficiency problems caused by repeated definitions and release of Variables
Defining and releasing variables also requires overhead. Repeated definition and releasing variables in a loop affect the program memory and performance. Therefore, moving the repeatedly defined and released variables in the loop out of the loop will improve the program efficiency.
Variables are defined inside the loop body:
For (INT I = 0; I <100; I ++)
{
Int K = 0;
If (A [I]> A [I + 1])
{
K = A [I];
A [I] = A [I + 1];
A [I + 1] = K;
}
}
Variables are defined outside the loop body:
Int K = 0;
For (INT I = 0; I <100; I ++)
{
If (A [I]> A [I + 1])
{
K = A [I];
A [I] = A [I + 1];
A [I + 1] = K;
}
}
3. efficiency problems caused by repeated function calls
Calling a function will cause a large overhead. repeated calls to the same function in a loop will cause a great waste. Therefore, you can create local variables, when a function is called in vitro and assigned to a local variable, You can reuse the local variable in the body of the loop to improve program efficiency.
Repeated function calls in the loop body:
Int arraysum (array myarray)
{
Int S = 0;
For (INT I = 0; I <myarray. Size (); I ++)
{
S + = myarray [I];
}
Return S;
}
Function called in vitro for circulation:
Int arraysum (array myarray)
{
Int S = 0;
Int K = myarray. Size ();
For (INT I = 0; I <K; I ++)
{
S + = myarray [I];
}
Return S;
}
4. efficiency problems caused by repeated use of member variables
Because the this pointer is used to obtain the base address of the member variable, the time for accessing the member variable is generally twice that of accessing the local variable. Therefore, you can create a local variable and assign a value in the external body of the loop, repeated use in the loop body will improve program efficiency.
Class Array
{
Int size;
Int array [100];
};
Reuse member variables:
Int array: sum ()
{
Int S = 0;
For (INT I = 0; I <size; I ++)
{
S + = array [I];
}
Return S;
}
Use local variables instead of member variables:
Int array: sum ()
{
Int S = 0;
Int K = size;
For (INT I = 0; I <K; I ++)
{
S + = array [I];
}
Return S;
}