Why is `{*l}` faster than `set(l)` - python sets (not really only for sets, for all sequences)

青春壹個敷衍的年華 提交于 2019-12-01 10:49:15

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!