a, b, c, d, e = [object() for _ in range(5)]
dict_symbols = {a : 'a', b : 'b', c : 'c', d : 'd', e : 'e'}
dict_strings = {'a' : 'a', 'b' : 'b', 'c' : 'c', 'd' : 'd', 'e' : 'e'}
def run_symbols():
for key in dict_symbols.keys():
dict_symbols[key]
def run_strings():
for key in dict_strings.keys():
dict_strings[key]
在 ipython 中测试速度:
In [3]: %timeit run_symbols
10000000 loops, best of 3: 33.2 ns per loop
In [4]: %timeit run_strings
10000000 loops, best of 3: 28.3 ns per loop