11. Python代码微优化之加快查找(将全局变量提到局部变量)
参考自: https://www.cnblogs.com/chengxuyuanaa/p/12849919.html
#_*_ encoding: utf-8 _*_ @author: ty hery 2020/6/4
from collections import OrderedDict
# collections.OrderedDict类:
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
return dict_setitem(self, key, value)
# 注意最后一个参数:dict_setitem=dict.setitem。如果你仔细想就会感觉有道理。将值关联到键上,
# 你只需要给setitem传递三个参数:要设置的键,与键关联的值,传递给内建dict类的setitem类方法。等会,好吧,
# 也许最后一个参数没什么意义。 最后一个参数其实是将一个函数绑定到局部作用域中的一个函数上。
# 具体是通过将dict.setitem赋值为参数的默认值。这里还有另一个例子:
def not_list_or_dict(value):
return not (isinstance(value, dict) or isinstance(value, list))
# 这里我们做同样的事情,把本来将会在内建命名空间中的对象绑定到局部作用域中去。因此,python将会使用LOCAL_FAST而不是
# LOAD_GLOBAL(全局查找)。那么这到底有多快呢?我们做个简单的测试:
# $ python -m timeit -s 'def not_list_or_dict(value): return not (isinstance(value, dict) or isinstance(value, list))'
# 'not_list_or_dict(50)'1000000 loops, best of 3: 0.48 usec per loop
#
# $ python -m timeit 'def not_list_or_dict(value, _isinstance=isinstance, _dict=dict, _list=list):return not (_isinstance(value, _dict) or _isinstance(value, _list))'
# 'not_list_or_dict(50)'1000000 loops, best of 3: 0.423 usec per loop
# 换句话说,大概有11.9%的提升 [2]。比我在文章开始处承诺的5%还多!
测试结果:
In [35]: def not_list_or_dict3(value):
...: return not (isinstance(value, dict) or isinstance(value, list))
...:
In [36]: def not_list_or_dict4(value, _isinstance=isinstance, _dict=dict, _list=list):
...: return not (_isinstance(value, _dict) or _isinstance(value, _list))
...:
In [37]: timeit(not_list_or_dict4)
100000000 loops, best of 3: 19.2 ns per loop
In [38]: timeit(not_list_or_dict3)
10000000 loops, best of 3: 20.8 ns per loop
In [39]: %timeit not_list_or_dict4
The slowest run took 64.90 times longer than the fastest. This could mean that an intermediate result is being cached.
100000000 loops, best of 3: 18.5 ns per loop
In [40]: %timeit not_list_or_dict3
10000000 loops, best of 3: 20.5 ns per loop
In [41]: 18
试了下,确实有小额度提升,但是不到,%7到%9之间
写入自己的博客中才能记得长久
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!