differences between “d = dict()” and “d = {}”

前端 未结 5 926
天涯浪人
天涯浪人 2020-12-02 11:42
$ python2.7 -m timeit \'d={}\'
10000000 loops, best of 3: 0.0331 usec per loop
$ python2.7 -m timeit \'d=dict()\'
1000000 loops, best of 3: 0.19 usec per loop
         


        
5条回答
  •  北海茫月
    2020-12-02 12:00

    Doug Hellmann wrote up an exhaustive comparison of the performance difference.

    tl;dr

    With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

提交回复
热议问题