4

So here is my timings:

>>> import timeit >>> timeit.timeit(lambda: set(l)) 0.7210583936611334 >>> timeit.timeit(lambda: {*l}) 0.5386332845236943 

Why is that, my opinion would be equal but it's not.

So unpacking is fast from this example, right?

2
  • 1
    The identifier set could be redefined so it needs an additional dictionary lookup but this would probably not explain the whole difference. Commented Nov 9, 2018 at 4:00
  • @MichaelButscher Thanks you for the comment, helped me :-) Commented Nov 9, 2018 at 4:02

1 Answer 1

6

For the same reason [] is faster than list(); the interpreter includes dedicated support for syntax based operations that uses specialized code paths, while constructor calls involve:

  1. Loading the constructor from built-in scope (requires a pair of dict lookups, one in global scope, then another in built-in scope when it fails)
  2. Requires dispatch through generic callable dispatch mechanisms, and generic argument parsing code, all of which is far more expensive than a single byte code that reads all of its arguments off the stack as a C array

All of these advantages relate to fixed overhead; the big-O of both approaches are the same, so {*range(10000)} won't be noticeably/reliably faster than set(range(10000)), because the actual construction work vastly outweighs the overhead of loading and calling the constructor via generic dispatch.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, [] is faster than list() too, wow good explanation, only can accept in 8 minutes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.