Performance comparison: insert vs build Python set operations

前端 未结 4 412
时光说笑
时光说笑 2021-02-02 17:14

In python, is it faster to a) Build a set from a list of n items b) Insert n items into a set?

I found this page (http://wiki.python.org/moin/TimeComplexity) but it did

4条回答
  •  时光说笑
    2021-02-02 17:53

    On my Thinkpad:

    In [37]: timeit.timeit('for a in x: y.add(a)',
                           'y=set(); x=range(10000)', number=10000)
    Out[37]: 12.18006706237793
    
    In [38]: timeit.timeit('y=set(x)', 'y=set(); x=range(10000)', number=10000)
    Out[38]: 3.8137960433959961
    

提交回复
热议问题