這樣一段代碼:
#include <cstdio>
#include <vector>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
using namespace std;
// len = 100
string s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
string t = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
bool comp1() {
for (int i=0;i<s.size();i++) {
if (s[i] != t[i]) return false;
}
return true;
}
bool comp2() {
return s == t;
}
int main() {
int maxn = 10000000; // 1百萬
clock_t t1 = clock();
for(int i=0;i<maxn;i++) {
comp1();
}
cout << (clock() - t1) * 1.0 / CLOCKS_PER_SEC << "s" << endl;
t1 = clock();
for(int i=0;i<maxn;i++) {
comp2();
}
cout << (clock() - t1) * 1.0 / CLOCKS_PER_SEC << "s" << endl;
}
1浪藻、兩個長度為100的相等的字符串比較1百萬次,兩種比較方式會相差多少呢?
14.4658s
0.280318s
差距達100倍客冈。。稳强。
2场仲、兩個長度為100的最后一個字符不相等的字符串比較1百萬次,兩種比較方式會相差多少呢退疫?
14.5281s
0.297259s
3渠缕、兩個長度為100的第一個字符不相等的字符串比較1百萬次,兩種比較方式會相差多少呢褒繁?
0.16233s
0.263476s
顯然應(yīng)該使用==運算符亦鳞,實現(xiàn)參考:https://stackoverflow.com/questions/4145840/the-way-to-compare-string-in-an-efficient-way-in-c