Public Group

# std::sort vs. list::sort

This topic is 1862 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I wanted to do a quick performance (very unscientific though) test on std::vector and std::list and I was very surprised by the results.  Maybe it's just me not understanding or knowing how each implements everything internally.

My surprise came when I sorted a vector vs. sorted a equally size linked list.  I understand that std::sort requires a random access iterator that std::list doesn't provide which is why their is a list::sort method.  Though I thought that using std::sort would require a swap internally (not sure why I do think that, I'm sure I should be doing more research about the internals of each) which wold require each and every object to be copied over.  Now the test object I use is just a very basic struct that "simulates" a Rectangle that has a length, width, x position, and y position, all stored as doubles.  I overloaded the < operator in it to do the sort and it should sort it based on area (just went ahead and calculated the length*width instead of storing an area member variable, not trying to make this scientific or find performances).

In my test I store 1,000,000 rectangles in a vector a list and set the length, width, xPosition, and yPosition to random numbers for each element in the vector.  I then set each elements length, width, xPosition, and yPosition in the list to the vectors corresponding element.  Calculate the time for each.  Maybe I should use a more scientific approach to this, as I am only using std::clock_t and CLOCKS_PER_SEC to calculate.

When doing this I am very surprised at the performance gap between the two!

First, here's my code to do this quick test, although it isn't anything special or scientific

// Tests Sorting Lists and Vectors Performance

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <ctime>

struct Rectangle
{
double length;
double width;
double xPosition;
double yPosition;

bool operator<(const Rectangle& rect) const
{
return (length*width) < (rect.length*rect.width);
}
};

int main()
{
const int NUM_ELEMENTS = 1000000;
std::clock_t startTime;
std::clock_t stopTime;

std::vector<Rectangle> myVector(NUM_ELEMENTS);
std::vector<Rectangle>::iterator vectIter;

// Insert rectangle data in vector
startTime = clock();
for(vectIter = myVector.begin(); vectIter != myVector.end(); ++vectIter)
{
vectIter->length = 1.0*rand()/RAND_MAX;
vectIter->width = 1.0*rand()/RAND_MAX;
vectIter->xPosition = 1.0*rand()/RAND_MAX;
vectIter->yPosition = 1.0*rand()/RAND_MAX;
}
stopTime = clock();
double totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
std::cout << "Inserted rectangles in vector in: " << totalTime <<std::endl;

std::list<Rectangle> myList(NUM_ELEMENTS);
std::list<Rectangle>::iterator listIter;

// Insert rectangle data in list
startTime = clock();
for(vectIter = myVector.begin(), listIter = myList.begin(); listIter != myList.end() && vectIter != myVector.end(); ++listIter, ++vectIter)
{
listIter->length = vectIter->length;
listIter->width = vectIter->width;
listIter->xPosition = vectIter->xPosition;
listIter->yPosition = vectIter->yPosition;
}
stopTime = clock();
totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
std::cout << "Inserted rectangles in list in: " << totalTime <<std::endl;

// sort the vector using std::sort algoorithm
startTime = clock();
std::sort(myVector.begin(), myVector.end());
stopTime = clock();
totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
std::cout << "Time for sorting a vector: " << totalTime << std::endl;

// sort the list
// can't use std::sort, use the list member function
startTime = clock();
myList.sort();
stopTime = clock();
totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
std::cout << "Time for sorting a list: " << totalTime << std::endl;

return 0;
} 

The output/performance I get

Inserted Rectangles in Vector in: 1.597

Inserted Rectangles in List in: 2.989

Time for sorting a vector: 3.384

Time for sorting a list: 111.252

What's with the HUGE perforamance decrease in sorting that list?  I understand list is slow at random access and that is what std::vector is strong at, but that big a performance hit when using a list?  I think list::sort uses a merge sort, which is O(NlogN), I believe.  What would std::sort be using in this case?  is their any guarantee or way to see what implementation it is using (maybe I didn't research enough), but does the standard guarantee what it will use? Is their a worst case Big-Oh run time that std::sort guarantees?  Average Big-Oh run time?

I understand that this isn't a scientific test nor would I use something like that in a real world code, but is their something just crazy wrong with my code that I'm missing that is causing the list to be that much slower?  I do still understand where benefits of using a list would come in, but if this is correct I can totally understand why I've always been told "look at std::vector first."  Is this correct?  Maybe it's because since the object I am sorting in each is very basic and if I was using a larger and more advanced class that would take longer to copy and results could be different?

Interested in any comments on this.

Note: this is just curiosity and I am not trying to pre-optimize current real world code that I have or anything.  Just my Computer Science brain being curious.

##### Share on other sites

I was just thinking about the cache misses when I was thinking that the std::list doesn't have to store the elements contiguously.  I did a bit more research and it seems the performance difference is more than likely hardware and cache misses with the std::list.

Thanks!

##### Share on other sites

Even if the list does miraculously store it's elements contiguously, it's still got the overhead of the next/prev pointers per node, which in your case for a 32-bit build, is an increase of 25% on the amount of memory that has to be moved from RAM to cache to RAM. CPUs have gotten so fast these days that many simple algorithms will be completely bottlenecked by memory access times.

Out of interest, you may want to run your tests again using floats and/or shorts and/or bytes for the Rectangle's members, and seeing if it affects the performance of the sort.

##### Share on other sites

I just ran the code to see what the results are in my machine, I am using mingw with gcc 4.7.1,

Debug mode :

Inserted rectangles in vector in: 0.072

Inserted rectangles in list in: 0.058

Time for sorting a vector: 0.53

Time for sorting a list: 0.916

Release Mode:

Inserted rectangles in vector in: 0.056

Inserted rectangles in list in: 0.016

Time for sorting a vector: 0.234

Time for sorting a list: 0.415

So, not much of a difference in my machine though

Edited by solewalker

##### Share on other sites

While we're at it, here are some clang++3.2 (Apple 4.2) results (I removed the "insertion" timings because it's not a fair test (inserting to the vector calls rand() and converts the int to double, whereas the list just copies a double)):

No optimizations, default standard library:

Time for sorting a vector: 0.388013
Time for sorting a list: 0.768855

No optimizations, libc++ library:
Time for sorting a vector: 0.258923
Time for sorting a list: 0.696469

O3 optimizations and NDEBUG, default standard library:
Time for sorting a vector: 0.091026
Time for sorting a list: 0.353424

O3 optimizations and NDEBUG, libc++ standard library:
Time for sorting a vector: 0.091312
Time for sorting a list: 0.309724

Running on Intel Core i7 2.7GHz with 256 KB L2 cache (per core) and 6 MB L3 cache.

Running it with long double gave slightly higher numbers (libc++, no optimizations):

Time for sorting a vector: 0.457013

Time for sorting a list: 0.760925

While running with char gave lower numbers (libc++, no optimizations):

Time for sorting a vector: 0.010401
Time for sorting a list: 0.13561

Indeed, I would blame your differences primarily on the cache.
Edited by Cornstalks

##### Share on other sites

This was using Visual Studio 2012.  Previous results were from debug build.  I never did post my results from a release build, with default optimization.

Release Build:

Time for sorting a vector: 0.136

Time for sorting a list: 0.455

When switching to a char, I get:

Time for sorting a vector: 0.002

Time for sorting a list: 0.045

This is on a Intel Core i7 6MB L3 Cache 2.3 GHz with 3.3 GHz Max Turbo (when program runs, speed jumped to 3.1 GHz until I closed it)

So seems like it Visual Studio 2012's Compiler is doing some heavy checking when compiled in Debug Mode

Tried it using highest optimization level and favoring speed in Visual Studio and results were pretty much exactly the same.  I would need to use a profiler if I wanted to start studying some differences more.

I would say this could also go and show the differences between debug and release builds.

Cornstalks: yea the time for the insertion wasn't fair.  I just did that really just to do it.  I wasn't really studying that nor basing the list results or vector results based on that.

##### Share on other sites

Profiling debug builds is generally a complete waste of time.

##### Share on other sites

This was using Visual Studio 2012.  Previous results were from debug build.  I never did post my results from a release build, with default optimization.

Release Build:

Time for sorting a vector: 0.136

Time for sorting a list: 0.455

So the results are within a factor of 4. This matches my expectations.

1. 1
2. 2
3. 3
4. 4
5. 5
Rutin
17

• 9
• 12
• 9
• 12
• 37
• ### Forum Statistics

• Total Topics
631420
• Total Posts
2999990
×