i++, ++i 和i=i+1究竟哪個(gè)快?
引子
以前學(xué)習(xí)C++時(shí),被告知i++的速度要比i=+1快,而++i的速度又要比i++快。即在效率上有:++i > i++ > i=i+1。所以如果單單只是需要進(jìn)行遞增時(shí),用++i是最好的。但是某天我突然覺(jué)得:這三個(gè)運(yùn)算的目的都是一樣,開(kāi)銷(xiāo)按道理應(yīng)該相同才對(duì)。難道編譯器如此之笨?就連這點(diǎn)優(yōu)化都不會(huì)做?
運(yùn)行時(shí)間測(cè)試(VS2008)
先用c#做了一遍:
static
private
void
Test()
{
int
counter = 0;
Stopwatch
timer = new
Stopwatch();
timer.Start();
for (int
i = 0; i < 2147483647; i++)
{
counter++;
}
timer.Stop();
Console.WriteLine("i++: " + timer.ElapsedMilliseconds);
timer.Reset();
counter=0;
timer.Start();
for (int
i = 0; i < 2147483647; ++i)
{
++counter;
}
timer.Stop();
Console.WriteLine("++i: " + timer.ElapsedMilliseconds);
timer.Reset();
counter=0;
timer.Start();
for (int
i = 0; i < 2147483647; i = i + 1)
{
counter=counter+1;
}
timer.Stop();
Console.WriteLine("i=i+1: "+timer.ElapsedMilliseconds);
Console.WriteLine();
}
從結(jié)果來(lái)看,幾乎沒(méi)有分別,每個(gè)算式都有機(jī)會(huì)獲得第一名。所以我覺(jué)得這3個(gè)算式對(duì)編譯器來(lái)說(shuō)應(yīng)該是沒(méi)有分別的。
用c++做了一遍
void
test()
{
int
elapTicks;
double
elapMilli;
clock_t
Begin, End;
int
counter = 0;
Begin = clock() * CLK_TCK; //start the timer
for(int
i=0; i<2147483647; i++) counter++;
End = clock() * CLK_TCK; //stop the timer
elapTicks = End - Begin; //the number of ticks from Begin to End
elapMilli = elapTicks/1000; //milliseconds from Begin to End
cout<<"i++: "<<elapMilli<<"\n";
counter=0;
Begin = clock() * CLK_TCK; //start the timer
for(int
i=0; i<2147483647; ++i) ++counter;
End = clock() * CLK_TCK; //stop the timer
elapTicks = End - Begin; //the number of ticks from Begin to End
elapMilli = elapTicks/1000; //milliseconds from Begin to End
cout<<"++i: "<<elapMilli<<"\n";
counter=0;
Begin = clock() * CLK_TCK; //start the timer
for(int
i=0; i<2147483647; i=i+1)counter=counter+1;
End = clock() * CLK_TCK; //stop the timer
elapTicks = End - Begin; //the number of ticks from Begin to End
elapMilli = elapTicks/1000; //milliseconds from Begin to End
cout<<"i=i+1: "<<elapMilli<<"\n\n";
}
結(jié)果也是類(lèi)似。
結(jié)論
i++, ++i 和i=i+1的區(qū)別,應(yīng)該只是純粹理論上的區(qū)別(即按照相應(yīng)的表達(dá)算式進(jìn)行編譯)。個(gè)人猜測(cè)對(duì)于以上3個(gè)表達(dá)式,編譯器在編譯之后應(yīng)該生成一樣的語(yǔ)句。不過(guò)我不懂匯編,也不懂如何進(jìn)一步深入測(cè)試。就此次測(cè)試的結(jié)果來(lái)看,3個(gè)表達(dá)式的時(shí)間開(kāi)銷(xiāo)是一樣的(每次運(yùn)行結(jié)果誤差應(yīng)該是其他原因)。當(dāng)然,此分析僅限于VS2008,有可能這3個(gè)語(yǔ)句在其他編譯器上的性能會(huì)有所不同。
歡迎指正。