Por que std :: vector :: operator [] é 5 a 10 vezes mais rápido que std :: vector :: at ()?
Durante a otimização do programa, tentando otimizar um loop que itera através de um vetor, descobri o seguinte fato: :: std :: vector :: at () é EXTREMAMENTE mais lento que o operador []!
O operador [] é 5 a 10 vezes mais rápido que em (), nas versões de lançamento e depuração (VS2008 x86).
Ler um pouco na web me fez perceber que at () tem verificação de limites. Ok, mas, retardando a operação em até 10 vezes ?!
Há alguma razão para isso? Quero dizer, a verificação de limites é uma comparação simples de números, ou estou faltando alguma coisa?
A questão é qual é o verdadeiro motivo desse sucesso no desempenho?
Além disso,existe alguma maneira de torná-lo ainda mais rápido?
Certamente vou trocar todas as minhas chamadas at () com [] em outras partes do código (nas quais eu já tenho verificação de limite personalizada!).
Prova de conceito:
#define _WIN32_WINNT 0x0400
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <conio.h>
#include <vector>
#define ELEMENTS_IN_VECTOR 1000000
int main()
{
__int64 freq, start, end, diff_Result;
if(!::QueryPerformanceFrequency((LARGE_INTEGER*)&freq))
throw "Not supported!";
freq /= 1000000; // microseconds!
::std::vector<int> vec;
vec.reserve(ELEMENTS_IN_VECTOR);
for(int i = 0; i < ELEMENTS_IN_VECTOR; i++)
vec.push_back(i);
int xyz = 0;
printf("Press any key to start!");
_getch();
printf(" Running speed test..\n");
{ // at()
::QueryPerformanceCounter((LARGE_INTEGER*)&start);
for(int i = 0; i < ELEMENTS_IN_VECTOR; i++)
xyz += vec.at(i);
::QueryPerformanceCounter((LARGE_INTEGER*)&end);
diff_Result = (end - start) / freq;
}
printf("Result\t\t: %u\n\n", diff_Result);
printf("Press any key to start!");
_getch();
printf(" Running speed test..\n");
{ // operator []
::QueryPerformanceCounter((LARGE_INTEGER*)&start);
for(int i = 0; i < ELEMENTS_IN_VECTOR; i++)
xyz -= vec[i];
::QueryPerformanceCounter((LARGE_INTEGER*)&end);
diff_Result = (end - start) / freq;
}
printf("Result\t\t: %u\n", diff_Result);
_getch();
return xyz;
}
Editar:
Agora, o valor está sendo atribuído a "xyz", portanto o compilador não o "limpará".