I want to know if there is a difference in performance of the below two 'for loops'. I know that the complexity of std::string.length() is constant ( O(1) ) in C++11. So I think there should be no performance difference in the two loops below.
Also, i am curious as to how C++11 calculates the length of a random string in constant time? Is there a way to look at its code?
Thanks.
1) Calculating s.length() only once
1 2 3 4 5 6 7 8 9 10
string s;
cout<<"Enter string to be converted to upper"<<endl;
cin>>s;
for(size_t i = 0 , j = s.length(); i < j; ++i )
{
//do something
}
2) Calculating s.length() on each iteration
1 2 3 4 5 6
for(size_t i = 0; i < s.length(); ++i )
{
//do something
}
As you know, a call to s.length() takes constant time and clearly retrieving the value of j takes constant time too, so the different is small, as long as those constants are comparable.
Pre-storing the length might be a little faster for 2 reasons. First, it ensures that the call to length() is made only once and function calls are often slow. Now there's an excellent chance that the compiler will optimize away the call to s.length() in your second example, so chances are good that this won't be an issue.
Second, since j is a local variable, it might get stored in a register and register access is faster than memory access. Again, this might get optimized away, but chances are lower than optimizing away the call itself.
In either case, the performance difference is likely to be small, especially if the body of the loop takes long to run compared to the check for the length. Don Knuth said "premature optimization is the root of most evil" and it really is true. In a case like this, the clarity of the second version of the code trumps the tiny speed advantage that the code provides. Unless you have concrete evidence that the speed matters, I wouldn't bother with it.
I am actually nervous sometimes while asking questions that sound very basic (or un-necessary to some), but so far i have always got a positive response on this forum. You are all great. Cheers.