Check following testPalindrome_index.cpp
program which utilizes string::operator[]:
#include <string>
bool isPalindrome(
std::string& s,
std::string::size_type start,
std::string::size_type end) {
auto count = (end - start + 1) / 2;
for (std::string::size_type i = 0; i < count; i++) {
if (s[start] != s[end]) {
return false;
}
start++;
end--;
}
return true;
}
int main() {
std::string s(1'000'000'000, 'a');
isPalindrome(s, 0, s.size() - 1);
return 0;
}
My compile is clang++
, and measure the execution time without & with optimization:
# c++ -std=c++14 testPalindrome_index.cpp -o index
# time ./index
0m13.84s real 0m12.77s user 0m01.06s system
# c++ -std=c++14 -O2 testPalindrome_index.cpp -o index
# time ./index
0m01.44s real 0m00.42s user 0m01.01s system
We can see the time differences are so large (13.84
vs 1.44
)!
Then change the code to use string::at:
#include <string>
bool isPalindrome(
std::string& s,
std::string::size_type start,
std::string::size_type end) {
auto count = (end - start + 1) / 2;
for (std::string::size_type i = 0; i < count; i++) {
if (s.at(start) != s.at(end)) {
return false;
}
start++;
end--;
}
return true;
}
int main() {
std::string s(1'000'000'000, 'a');
isPalindrome(s, 0, s.size() - 1);
return 0;
}
Compile and test again:
# c++ -std=c++14 testPalindrome_at.cpp -o at
# time ./at
0m07.31s real 0m06.36s user 0m00.96s system
# c++ -std=c++14 -O2 testPalindrome_at.cpp -o at
# time ./at
0m06.42s real 0m05.45s user 0m00.97s system
We can see the time gap is nearly 1
second, and not outstanding as the first case. But the time with “-O2
” optimization is 6.42
, far bigger than 1.44
which uses string::operator[]
.
The conclusion is if the string is long enough, the performance bias of using string::operator[]
and string::at
is remarkable. So this factor should be considered when decide which function should be used.
P.S., the full code isĀ here.