发现forward_list不比list插入更快啊.
C++11的forward_list在cppreference上面是这样说的:
Forward list is a container which supports fast insertion and removal of elements from anywhere from the container. Fast random access is not supported. It is implemented as singly-linked list and essentially does not have any overhead compared to its implementation in C. Compared to std::list this container provides more space efficient storage, when bidirectional iteration is not needed.
号称插入和删除更快。但是我在windows上面的VC10测试了一下release版,发现不是这么回事。我用windows的高精计时器跑了一下,list的插入操作用了6106ms,forward_list用了6199ms。运行了很多次forward_list都多用了1.5%的时间。这是为什么呢,难道我的代码本身有问题?
#include "stdafx.h" #include<Windows.h> #include<forward_list> #include<list> using namespace std; LARGE_INTEGER Frequency,PerformanceCount1,PerformanceCount2; void fTime1(){ QueryPerformanceCounter(&PerformanceCount1); } void fTime2(){ QueryPerformanceCounter(&PerformanceCount2); int tdiff=static_cast<int>(( ((PerformanceCount2.QuadPart - PerformanceCount1.QuadPart) * 1000)/Frequency.QuadPart)); printf("%d\n",tdiff); } int main(void){ const size_t nLoop=20000000; QueryPerformanceFrequency(&Frequency); { fTime1(); list<int> li; for(int i=0;i<nLoop;++i){ li.push_front(i); } auto it=li.begin(); ++it; for(int i=0;i<nLoop;++i){ li.insert(it,i);//相当于insert_after begin(); } fTime2(); } { fTime1(); forward_list<int> fi; for(int i=0;i<nLoop;++i){ fi.push_front(i); } for(int i=0;i<nLoop;++i){ fi.insert_after(fi.begin(),i); } fTime2(); } return 0; }