データを探索するときのsetと辞書型の速度比較
前回のリストと辞書型の比較のあとsetを使えば高速化できることを思い出したので,再計測
プログラム
#-*- coding:utf-8 -*- import time a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] b = {'a':1, 'b':1, 'c':1, 'd':1, 'e':1, 'f':1, 'g':1, 'h':1, 'i':1, 'j':1, 'k':1} def test_a(): if 'c' in set(a): print 'a' def test_b(): if b.has_key('c'): print 'a' if __name__=='__main__': f = time.clock() test_a() t = time.clock() print t-f f = time.clock() test_b() t = time.clock() print t-f
結果
- 1回目
set 0.000515455413657
辞書型 0.00159805842683
- 1回目
set 0.000505923521228
辞書型 0.0017304050871
- 1回目
set 0.000502624020002
辞書型 0.00179529527786
- 1回目
set 0.000560915208318
辞書型 0.00254831477975
- 1回目
set 0.000409504763197
辞書型 0.00180849328277
感想
setのほうが断然早かった.
リストのまま検索してる人は,必ずsetに直しましょう!