Code:
#include <vector>
#include <cstdio>
#include <cstring>
using namespace std;
void f(const char* s) {
for (size_t i = 0; i < strlen(s); i++) {
printf("%c ", s[i]);
}
}
void g(const vector<int>& v) {
for (size_t i = 0; i < v.size(); i++) {
printf("%d ", v[i]);
}
}
Compile link: https://godbolt.org/z/PCi5yg
You will see the assembly code:
- In function
f(),strlen(s)gets called every time; - But in function
g(),v.size()gets called only once.
Why is that?
The parameters are const, and they didn't change parameter in the inner loop.