相关疑难解决方法(0)

为什么[]比list()更快?

我最近比较了处理速度[]和,list()并且惊讶地发现它的[]运行速度比它三倍list().我跑了相同的测试与{}dict(),结果几乎相同:[]{}两个花了大约0.128sec /百万次,而list()dict()大约花费每个0.428sec /万次.

为什么是这样?不要[]{}(可能()'',太)立即传回文字的一些空股票的份,而其明确命名同行(list(),dict(),tuple(),str())完全去创建一个对象,他们是否真的有元素?

我不知道这两种方法有何不同,但我很想知道.我无法在文档中或在SO上找到答案,搜索空括号结果比我预期的问题更多.

我拨打了我的时序结果timeit.timeit("[]")timeit.timeit("list()"),和timeit.timeit("{}")timeit.timeit("dict()"),分别比较列表和字典.我正在运行Python 2.7.9.

我最近发现的" 为什么是,如果真慢于如果为1? "来比较的性能if Trueif 1,似乎触及了类似的文字,对全局的情况; 也许值得考虑一下.

python performance list instantiation literals

679
推荐指数
5
解决办法
7万
查看次数

为什么dict.get(key)比dict [key]运行得慢

在运行数值积分器时,我注意到速度的明显差异取决于我如何在字典中提取字段的值

import numpy as np

def bad_get(mydict):
    '''Extract the name field using get()'''
    output = mydict.get('name', None)
    return output

def good_get(mydict):
    '''Extract the name field using if-else'''
    if 'name' in mydict:
        output = mydict['name']
    else:
        output = None
    return output


name_dict = dict()
name_dict['name'] = np.zeros((5000,5000))
Run Code Online (Sandbox Code Playgroud)

在我的系统上,我注意到以下区别(使用iPython)

%%timeit
bad_get(name_dict) 

The slowest run took 7.75 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 247 ns per loop
Run Code Online (Sandbox Code Playgroud)

相比

%%timeit …
Run Code Online (Sandbox Code Playgroud)

python performance dictionary

7
推荐指数
1
解决办法
1506
查看次数

标签 统计

performance ×2

python ×2

dictionary ×1

instantiation ×1

list ×1

literals ×1