python - 为什么 dict 文字语法优于 dict 构造函数?

标签 python dictionary object-literal

为什么 Python dict 构造函数比 using 字面量语法慢?

经过和同事的激烈争论,我做了一些比较,得到了如下统计数据:

python2.7 -m timeit "d = dict(x=1, y=2, z=3)"
1000000 loops, best of 3: 0.47 usec per loop

python2.7 -m timeit "d = {'x': 1, 'y': 2, 'z': 3}"
10000000 loops, best of 3: 0.162 usec per loop

构造函数变慢的原因是什么?如果有的话,在什么情况下会更快?

最佳答案

构造函数较慢,因为它通过调用 dict() 函数创建对象,而编译器将 dict 文字转换为 BUILD_MAP字节码,保存函数调用。

关于python - 为什么 dict 文字语法优于 dict 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309291/

相关文章:

python - 无论操作系统如何,Python zipfile 是否始终使用 posixpath 文件名?

python - 删除Python字典中的重复值

java - map 自动排序

javascript - 使用对象字面量定义构造函数原型(prototype)

JavaScript 对象文字 "this"关键字 jQuery 回调参数传递

Python - 在程序外保存数据

python - 在 python 中对列表或列表列表进行字符串化并将其转换回原始形式的问题

python - 为什么 `type(myField)` 返回 `<type ' 实例' >` and not ` <type 'Field' >`?

java - 如何在请求正文中将 map 从 Angular 客户端正确发送到 Spring Boot Controller ?收到的 map 总是空的

javascript - 如何在 JavaScript 对象文字中使用变量作为键?