Last time, it was confirmed in an experiment that the reference of the element in list is very slow compared to the dictionary and set type. http://qiita.com/cof/items/05f6ffc6d4e5b062aaa9 However, dictionary comprehensions should be fairly fast. I wondered if it would be explosive if I made a dictionary comprehension every time before referring to it, so I looked it up.
python2.7 windows7 Intel Core i5 CPU 2.4GHz Memory 4.0 GB
I checked it by referring to 10000 elements of the following two codes and measuring the time when it was executed 10 times. Number of elements 10000 Element in list Element in {Element: True for Element in List}
Element in list 10.226 Element in {Element: True for Element in List} 124.887
It wasn't fast to make a dictionary comprehension every time.
def in_list(n):
ls = [i for i in range(n)]
for i in range(n): i in ls
def in_dict(n):
ls = [i for i in range(n)]
for i in range(n): i in {i:True for i in ls}
def exe(func,num=100):
from timeit import timeit
setup = 'from __main__ import ' + func.split('(')[0]
print "%s: %s" % (func, timeit(func, setup, number=num))
if __name__=='__main__':
q = 10**4
exe('in_list(%d)'%q,10)
exe('in_dict(%d)'%q,10)
Recommended Posts