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 = ""; string b; 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?
EDIT: I followed the suggestion of NathanOliver and I addedd separate strings for each loop, so now the code looks like this:
#include <string> #include <iostream> #include <ctime> using namespace std; int main() { clock_t timer; string compare_string_1 = ""; string compare_string_2 = ""; string segment_1 = ""; string segment_2 = ""; for (int i = 0; i < 100000000; i++) compare_string_1 += "a"; for (int i = 0; i < 100000000; i++) compare_string_2 += "a"; timer = clock(); for (int i = 0; i < 100000000; i++) { if ('b'==compare_string_1.at(i)) segment_1 += "a"; } cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl; timer = clock(); for (int i = 0; i < 100000000; i++) { char c = compare_string_2.at(i); if ('b'==c) segment_2 += "a"; } cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl; return 0; }
bdeclared that you are using inb += "a";charvariable takes literally no time at all. The generated code is most likely identical for the two loops (puta.at(i)into register, compare register with'b'). (That's not your actual code, though -bis never declared. Copy and paste is a lost art, it seems.)