在各种情况下,我观察到链表迭代在C++中始终比在Go中慢10-15%.我在Stack Overflow上解决这个谜团的第一次尝试就在这里.我编码的例子有问题,因为:
1)由于堆分配,内存访问是不可预测的,并且
2)因为没有实际工作,一些人的编译器正在优化主循环.
为解决这些问题,我有一个新程序,包含C++和Go中的实现.C++版本需要1.75秒,而Go版本需要1.48秒.这次,我在计时开始之前做了一个大的堆分配,并用它来操作一个对象池,我从该对象池中释放并获取链表的节点.这样,内存访问应该在两个实现之间完全类似.
希望这使得神秘更具可重复性!
C++:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/timer.hpp>
using namespace std;
struct Node {
Node *next; // 8 bytes
int age; // 4 bytes
};
// Object pool, where every free slot points to the previous free slot
template<typename T, int n>
struct ObjPool
{
typedef T* pointer;
typedef pointer* metapointer;
ObjPool() :
_top(NULL),
_size(0)
{
pointer chunks = new T[n];
for (int i=0; i < n; …Run Code Online (Sandbox Code Playgroud)