I got curious with the difference between a for(;;)
and for(:)
,
particularly with the speed between the two. So I ran a little test by having a vector of 10 million integers and adding them all together in a for. I found that the for(:)
was 1.3 slower.
What would cause the for(:)
to be that much slower!?
EDIT: It seems like the for(:) uses the iterator of the vector unlike the for(;;) making it longer.
/Yu"stdafx.h" /GS /analyze- /W3 /Zc:wchar_t /ZI /Gm /Od /sdl /Fd"Debug\vc120.pdb" /fp:precise /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /Fa"Debug\" /EHsc /nologo /Fo"Debug\" /Fp"Debug\forvsForLoop.pch"
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <chrono>
void init(std::vector<int> &array){
srand(20);
for (int x = 0; x < 10000000; x++)
array.push_back(rand());
return;
}
unsigned long testForLoop(std::vector<int> &array){
unsigned long result = 0;
for (int x = 0; x < array.size(); x++)
result += array[x];
return result;
}
unsigned long testFor(std::vector<int> &array){
unsigned long result = 0;
for (const int &element : array)
result += element;
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> testingArray;
init(testingArray);
//Warm up
std::cout << "warming up \n";
testForLoop(testingArray);
testFor(testingArray);
testForLoop(testingArray);
testFor(testingArray);
testForLoop(testingArray);
testFor(testingArray);
std::cout << "starting \n";
auto start = std::chrono::high_resolution_clock::now();
testForLoop(testingArray);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "ForLoop took: " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;
start = std::chrono::high_resolution_clock::now();
testFor(testingArray);
end = std::chrono::high_resolution_clock::now();
std::cout << "For---- took: " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;
system("pause");
return 0;
}
/Od
,/D_DEBUG
etc.). That's like determining the fastest runner by measuring who can read maps best. Turn optimisations on and try again. – Angew is no longer proud of SO