Linked List vs Vector – Insert/Remove Performance Comparison

algorithmscperformance

I was reading this blog post: http://kjellkod.wordpress.com/2012/02/25/why-you-should-never-ever-ever-use-linked-list-in-your-code-again/

and I found there a code to run: http://ideone.com/62Emz

I've compiled it using gcc 4.7.2 with g++ -std=c++11 on my old laptop with T5450 cpu with two cores with 32 Kbytes L1 cache each and 2 Megabytes of (common?) L2 cache and I have got this results:

********** Times in microseconds**********
Elements ADD (List, Vector)     ERASE(List, Vector)
100,     , 0, 0,                0, 0
200,     , 0, 0,                15625, 0
500,     , 0, 0,                0, 0
1000,    , 15625, 0,            0, 15625
4000,    , 109375, 140625,              46875, 31250
10000,   , 750000, 875000,              312500, 187500
20000,   , 2968750, 3468750,            1296875, 781250
40000,   , 12000000, 13843750,          5359375, 3156250
Exiting test,. the whole measuring took 45375 milliseconds (45seconds or 0 minut
es)

Which actually says an opposite, at least for ADD operation comparing to what author of that blog post says. List is faster for ADD than Vector. What conclusions should I make from my results? Does it proof anything? What should I think or understand?

Best Answer

First of all, congratulations for doing the right thing and measuring rather than believing advice about efficiency! With modern computer architecture, it is harder than ever to predict how precisely a small change in data structures will affect runtimes, because of the many levels of the memory hierarchy, out-of-order execution, aggressive code optimizers etc. If your use case is indeed what you have measured, then yes, you will be better off with a list.

That said, that program doesn't do a lot; in practice you will almost certainly access elements more often than you add or delete them, and probably in non-successive ways. I suspect that if you rerun benchmarks with a lot of random accesses, the results might turn around, but... remember what I just said? Never assume. Always measure. Happy profiling!

Related Topic