Meh*_*dad 8 c++ string performance destructor vector
是否有一个众所周知的解决方案来解决以下问题?
你有很多字符串的向量
你快乐地用几十万个字符串填充它,它很快
你以任意方式操纵你的弦乐; 生活很好.
你完成了矢量; 矢量超出了范围,现在你必须去拿一些咖啡并坐下来,同时每个字符串逐个被摧毁.
我只是在同一台计算机上运行Linux下面的代码,这很好,这让我找到了解决方案.事实证明,这是我的系统 - 很久以前我曾经引起过的,但我忘记了这一点.
在解决问题后,时间急剧下降,甚至比GCC更好!
这是一个很好的谜题,所以我不会发布答案,而是会做其他的事情:
我现在不允许对这个问题给予赏金,但如果你认为你知道原因,那就试一试吧.如果它是正确的,我会接受它并给你一个很好的赏金.(提醒我,如果我忘记给你赏金!)
如果没有人知道那么我会在一段时间过后自己发布.
我曾经像任何人一样持怀疑态度,但现在我猜人们确实有一点他们STL很慢!
我的笔记本电脑花了3.95秒:(洗牌很关键)
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
int main()
{
using namespace std;
srand((unsigned)time(NULL));
clock_t start;
{
vector<string> v(400000);
for (size_t i = 0; i < v.size(); i++)
{
v[i].resize(16 + rand() % 32); // some variation
}
// shuffle
for (size_t i = 0; i < (size_t)pow((double)v.size(), 1.15); i++)
{
size_t j = rand() * (RAND_MAX + 1) + rand();
swap(v[i % v.size()], v[j % v.size()]);
}
printf("Going out of scope...\n"); fflush(stdout);
start = clock();
}
clock_t end = clock();
printf("%u ms\n", (end - start) * 1000 / CLOCKS_PER_SEC);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我看来,这个程序在内部使用一些O(n 2)算法,无论是在Visual C++中还是在Windows中.不确定发生了什么,但有趣的是......