Why is Python "sorted ()" slower than ", then .sort ()"

Here is the code I ran:

import timeit print timeit.Timer('''a = sorted(x)''', '''x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]''').timeit(number = 1000) print timeit.Timer('''a=x[:];a.sort()''', '''x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]''').timeit(number = 1000) 

and here are the results:

 0.00259663215837 0.00207390190177 

I would like to know why using .sort () is faster than sorted (), although both of them copy lists?

Note. I am running Python 2.7 on 2.53Ghz i5 with Win7

+7
source share
2 answers

The difference you are looking at is negligible and goes all the way to longer lists. Just adding * 1000 to the x definition gives the following results on my machine:

 2.74775004387 2.7489669323 

My best suggestion that sorted() was a bit slower for you is that sorted() needs to use some kind of generic code that can copy any iterable to the list, while copying the list directly can make an assumption that source is also a list. The sort code used by CPython is actually the same for list.sort() and sorted() , so not what makes the difference.

Change The source code for the current development version of sorted() in morality. p>

 a = list(x) a.sort() 

and, indeed, using this code instead of your second version eliminates any significant speed differences for any list sizes.

+8
source

In support of @Sven Marnach's answer :

There is a slight difference for small lists:

 $ python2.7 -mtimeit -s "x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]; s=sorted" "a=s(x)" 1000000 loops, best of 3: 1.87 usec per loop $ python2.7 -mtimeit -s "x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]" "a=x[:];a.sort()" 1000000 loops, best of 3: 1.66 usec per loop 

The difference goes from * 1000 (larger lists):

 $ python2.7 -mtimeit -s "x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]*1000; s=sorted" "a=s(x)" 100 loops, best of 3: 3.42 msec per loop $ python2.7 -mtimeit -s "x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]*1000" "a=x[:];a.sort()" 100 loops, best of 3: 3.48 msec per loop 
+1
source

All Articles