Is there a difference between using a dict literal and a dict constructor?

前端 未结 10 2113
深忆病人
深忆病人 2020-11-28 02:26

Using PyCharm, I noticed it offers to convert a dict literal:

d = {
    \'one\': \'1\',
    \'two\': \'2\',
}

10条回答
  •  被撕碎了的回忆
    2020-11-28 02:37

    Literal is much faster, since it uses optimized BUILD_MAP and STORE_MAP opcodes rather than generic CALL_FUNCTION:

    > python2.7 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
    1000000 loops, best of 3: 0.958 usec per loop
    
    > python2.7 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
    1000000 loops, best of 3: 0.479 usec per loop
    
    > python3.2 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
    1000000 loops, best of 3: 0.975 usec per loop
    
    > python3.2 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
    1000000 loops, best of 3: 0.409 usec per loop
    

提交回复
热议问题