1.16 dict() 与 {} 生成空字典有什么区别? ======================================== .. image:: http://image.iswbm.com/20200804124133.png 在初始化一个空字典时,有的人会写 dict(),而有的人会写成 {} 很多人会想当然的认为二者是等同的,但实际情况却不是这样的。 在运行效率上,{} 会比 dict() 快三倍左右。 使用 timeit 模块,可以轻松测出这个结果 .. code:: shell $ python -m timeit -n 1000000 -r 5 -v "dict()" raw times: 0.0996 0.0975 0.0969 0.0969 0.0994 1000000 loops, best of 5: 0.0969 usec per loop $ $ python -m timeit -n 1000000 -r 5 -v "{}" raw times: 0.0305 0.0283 0.0272 0.03 0.0317 1000000 loops, best of 5: 0.0272 usec per loop 那为什么会这样呢? 探究这个过程,可以使用 dis 模块 当使用 {} 时 .. code:: shell $ cat demo.py {} $ $ python -m dis demo.py 1 0 BUILD_MAP 0 2 POP_TOP 4 LOAD_CONST 0 (None) 6 RETURN_VALUE 当使用 dict() 时: .. code:: shell $ cat demo.py dict() $ $ python -m dis demo.py 1 0 LOAD_NAME 0 (dict) 2 CALL_FUNCTION 0 4 POP_TOP 6 LOAD_CONST 0 (None) 8 RETURN_VALUE 可以发现使用 dict(),会多了个调用函数的过程,而这个过程会有进出栈的操作,相对更加耗时。