不,Python字符串的长度几乎不会影响字典性能。字符串长度可能具有的唯一影响是在所
hash()使用的函数上,将键映射到哈希表插槽。
字符串长度对以下各项的性能影响很小
hash():
>>> import random>>> from timeit import timeit>>> from string import ascii_letters>>> generate_text = lambda len: ''.join([random.choice(ascii_letters) for _ in xrange(len)])>>> for i in range(8):... length = 10 + 10 ** i... testword = generate_text(length)... timing = timeit('hash(t)', 'from __main__ import testword as t')... print 'Length: {}, timing: {}'.format(length, timing)... Length: 11, timing: 0.061537027359Length: 20, timing: 0.0796310901642Length: 110, timing: 0.0631730556488Length: 1010, timing: 0.0606122016907Length: 10010, timing: 0.0613977909088Length: 100010, timing: 0.0607581138611Length: 1000010, timing: 0.0672461986542Length: 10000010, timing: 0.080118894577我停止生成1000万个字符的字符串,因为我不必等待笔记本电脑生成1亿个字符串。
时间几乎是恒定的,因为一旦计算出该值实际上就缓存在字符串对象上。



