我正在非常困倦地分析我的应用程序,它显示我的函数花费的时间分别有 25% 和 23% 用于执行新建和删除。我不明白这是在哪里发生的。那么有人可以告诉我这是在我的代码中发生的位置吗?
inline FixParser(fixmessage& tokenMap, const std::string& str) {
static seperator sep_delim("\x01");
static seperator sep_equal("=");
static std::string error("ERROR: ");
static FixKey fix_Key;
static tokenizer token_equal(error);
static tokenizer token_delim(error);
static tokenizer::iterator itr;
token_delim.assign(str, sep_delim);
int key;
try {
for(tokenizer::iterator it = token_delim.begin();
it != token_delim.end(); ++it) {
token_equal.assign(*it, sep_equal);
itr = token_equal.begin();
key = boost::lexical_cast<int>(*itr);
if(fix_Key.keys.find(key) == fix_Key.keys.end()) continue;
++itr;
const std::string& value(*itr);
tokenMap.insert(std::pair<int, std::string>(key, value));
}
} catch(boost::bad_lexical_cast &) {
std::cerr << error << str << std::endl;
return;
}
}
请原谅使用 static
它们稍后将被删除并放置在 struct
中。
最佳答案
请注意:有很多 字符串被复制。每个字符串都会调用 new
来获取内存并调用 delete
来释放它。
如果性能很重要并且您有能力保留 str
的拷贝,您可能希望改用索引。也就是说,让标记成为索引对(开始、结束)而不是完整的字符串。这样显然更容易出错。
此外,tokenMap
为映射中的每个条目分配一个节点,如果您有很多条目,将会有很多节点(因此要创建 new
他们)。您可能想改用 deque
,并在完成后对项目进行排序,除非您确实需要 map
提供的功能(自动重复数据删除)。
Bikeshedd 版本,删除了大部分静态变量(无法控制自己):
inline FixParser(fixmessage& tokenMap, const std::string& str) {
static seperator sep_delim("\x01");
static seperator sep_equal("=");
static FixKey const fix_Key;
try {
tokenizer token_delim(str, sep_delim);
// avoid computing token_delim.end() at each iteration
for(tokenizer::iterator it = token_delim.begin(), end = token_delim.end();
it != end; ++it)
{
tokenizer token_equal(*it, sep_equal);
tokenizer::iterator itr = token_equal.begin();
int const key = boost::lexical_cast<int>(*itr);
if(fix_Key.keys.find(key) == fix_Key.keys.end()) continue;
++itr;
tokenMap.insert(std::make_pair(key, *itr));
}
} catch(boost::bad_lexical_cast &) {
std::cerr << error << str << std::endl;
return;
}
}
关于c++ - 隐式的 new 和 delete 运算符杀死性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10416743/