キー付きのマップを使用していましたがstd::string
、すべてが正常に機能していましたが、期待したパフォーマンスが得られませんでした。最適化できるところを探して少しだけ改善したところ、同僚から「あの弦のキーが遅くなる」と言われました。
私は何十もの質問を読みましたが、彼らは一貫して次のように言っています:
char *
「 a をキーとして使用しないでください」
「std::string
キーがボトルネックになることはありません」 「aと a
のパフォーマンスの違いは神話です。」char *
std::string
しぶしぶchar *
キーを試してみると、違い、大きな違いがありました。
問題を簡単な例に要約しました。
#include <stdio.h>
#include <stdlib.h>
#include <map>
#ifdef USE_STRING
#include <string>
typedef std::map<std::string, int> Map;
#else
#include <string.h>
struct char_cmp {
bool operator () (const char *a,const char *b) const
{
return strcmp(a,b)<0;
}
};
typedef std::map<const char *, int, char_cmp> Map;
#endif
Map m;
bool test(const char *s)
{
Map::iterator it = m.find(s);
return it != m.end();
}
int main(int argc, char *argv[])
{
m.insert( Map::value_type("hello", 42) );
const int lcount = atoi(argv[1]);
for (int i=0 ; i<lcount ; i++) test("hello");
}
まず std::string バージョン:
$ g++ -O3 -o test test.cpp -DUSE_STRING
$ time ./test 20000000
real 0m1.893s
次に 'char *' バージョン:
g++ -O3 -o test test.cpp
$ time ./test 20000000
real 0m0.465s
これはかなり大きなパフォーマンスの違いであり、より大きなプログラムで見たのとほぼ同じ違いです。
キーを使用すると、char *
キーを解放するのが面倒で、気分が悪くなります。C++ の専門家には何が欠けていますか? 何か考えや提案はありますか?