So I wanted to see by how much the performance of a program can be improved by not copying the value of a variable into another variable before comparing it (this will be explained better in the examples), and I noticed something weird. I had these two code segments:
string a = "";
for (int i = 0; i < 1000000; i++) a += 'a';
for (int i = 0; i < 1000000; i++) {
if ('b' == a.at(i));//compare the two chars directly
}
and
string a = "";
for (int i = 0; i < 100000000; i++) a += 'a';
for (int i = 0; i < 100000000; i++) {
char c = a.at(i);//declare a new variable
if ('b' == c);//compare the char with the newly created variable,
//instead of comparing it to the other char directly
}
I thought that the second segment would take longer to be executed, since there there is one more variable declared, compared to the first segment. When I actually timed the two I found that the second one took less time than the first one. I timed it a few times, and the second one always seems to take around 0.13 seconds less time to be executed. Here is the complete code:
#include <string>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
clock_t timer;
string a = "";
for (int i = 0; i < 100000000; i++)
a += "a";
timer = clock();
for (int i = 0; i < 100000000; i++) {
if ('b'==a.at(i)) b += "a";
}
cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl;
timer = clock();
for (int i = 0; i < 100000000; i++) {
char c = a.at(i);
if ('b'==c) b += "a";
}
cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl;
return 0;
}
Why does this happen?
Aucun commentaire:
Enregistrer un commentaire