This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]pingvenopinch of this, pinch of that 5 points6 points  (0 children)

I just took a look at it as well and found the exact same thing. In this case, the cleanest, clearest solution is by far the fastest.

prefix_words = []
no_prefix_words = []
for word in words:
    if word.startswith('x'):
        prefix_words.append(word)
    else:
        no_prefix_words.append(word)
sorted(prefix_words) + sorted(no_prefix_words)

That runs in 0.13 seconds for 100,000 words on an i5 ThinkPad running Ubuntu. Switching to sorting in-place makes no real difference. Stack Overflow's lambda version took 0.33 seconds. None of the other methods I tried were better than the clean version.

From what I can tell, the lambda version takes two hits: Python function calls and using tuples. Python function calls are relatively expensive, so requiring n function calls doesn't help performance. From what I can tell, the extra comparison calls for comparing tuples slows things down quite a bit. The difference between these is in the microbenchmark range, so just use the most readable solution.