In the Transforming Code into Beautiful, Idiomatic Python video (link starts at 10:07), the speaker says that using key instead of the cmp comparison function for sorting is more efficient. To paraphrase: he states that because there are O(nlog(n)) comparisons, a comparison function would be called 20m times for a 1m element list (log2(1m) ~ 20) while using key is better because it is called exactly once per key.
I understand his point about how using key is more readable, but I don't get how he determined that it's called once per key. I would have thought that under the hood, a sorting function that has a key parameter would look something like this:
def sort(sequence, key=None):
if key is None:
key = lambda x: x
def compare(first, second):
if key(first) < key(second): return -1
if key(second) < key(first): return 1
return 0
# ... implement sorting algorithm
And so it would amount to the same time complexity whether we use a key function or a comparison function.
How is the key function only called once per element, if there are O(nlog(n)) comparisons? Is this a Timsort implementation detail?
Edit:
To address the comment asking for an example:
In python2, the sorted function accepted a cmp argument, something like this:
def compare(first, second):
if len(first) < len(second): return -1
if len(second) < len(first): return 1
return 0
sorted(my_list, cmp=compare)
However, you could also pass a key function if you wanted. So, to achieve the same effect as above, you would do this:
sorted(my_list, key=len)
In the video, the author claims that the second option is more efficient than the first.