C++ benchmarks: vector vs list vs deque

This post shows the results of several benchmarks I wrote to verify the performance of 3 C++ STL containers: vector, list and deque. The operations tested are insertion at the end of the container, insertion at random positions and removal of elements from random positions.

Intro

Last night a video on Reddit caught my attention: “Bjarne Stroustrup: Why you should avoid Linked Lists“. Basically it’s a 8 minutes video in which Bjarne Stroustrup tells you to not use linked lists because they suck.

After watching the video and assuming Stroustrup was obviously right, I decided to write few benchmarks to test how much linked lists suck perform compared to other STL containers.

Disclaimer

These are synthetic tests based on spaghetti-code I wrote without considering any kind of optimization or coding / design style, they test exclusively STL containers and I ran them only on my Linux machine.

Things could be totally different in your program running your code on a different machine.

The Benchmarks

I wrote 3 benchmarks which are based on 3 different STL containers: vector, list, deque. All the benchmarks perform creation or destruction of a different number of objects which are based on a simple class containing 4 ints and few functions.

The first one tests the performance of adding objects at the end of the container using the push_back function.

The second one tests the performance of inserting objects at random positions using the insert function.

The Third one tests the performance of removing object from random positions using the erase function.

Results

Here the results of running the 3 benchmarks with 1000, 5000, 10000 and 25000 objects.

The tests were executed on a 64-bit Kubuntu Linux 13.10 machine powered by an Intel i7-4770 CPU @ 3.40GHz and 8Gb of DDR3 RAM.

All the times are in milliseconds, lower values (green) are better.

push_back

1000 5000 10000 25000 std::vector 0 0 0 1 std::list 0 0 1 2 std::deque 0 0 0 1

insert

1000 5000 10000 25000 std::vector 0 7 25 140 std::list 2 50 272 1893 std::deque 0 4 17 111

erase

1000 5000 10000 25000 std::vector 0 5 22 139 std::list 1 69 395 2712 std::deque 0 5 18 126

It’s easy to see the pattern here… according to these tests at least, push_back is a (virtually) free operation for any container, but for everything else list is the worst performing container, whereas deque is the best one.

Source Code

You can download the source code of these benchmarks and run them on your machine, then feel free to post your results here commenting this post.