A little benchmark for you (ipython):
In [1]: def test_1(d, k):
...: if k in d:
...: var1 = d[k]
...:
In [2]: def test_2(d, k):
...: if d.has_key(k):
...: var1 = d[k]
...:
In [3]: def test_3(d, k):
...: try:
...: var1 = d[k]
...: except KeyError as e:
...: pass
...:
In [4]: def test_4(d, k):
...: if d.get(k):
...: var1 = d[k]
...:
In [5]: my_dict = {'key{}'.format(i): 'value{}'.format(i) for i in range(1000)}
In [6]: key_valid = "key5"
In [7]: key_non_valid = "key"
In [8]: %timeit test_1(my_dict, key_valid)
10000000 loops, best of 3: 172 ns per loop
In [9]: %timeit test_1(my_dict, key_non_valid)
10000000 loops, best of 3: 132 ns per loop
In [10]: %timeit test_2(my_dict, key_valid)
1000000 loops, best of 3: 211 ns per loop
In [11]: %timeit test_2(my_dict, key_non_valid)
10000000 loops, best of 3: 171 ns per loop
In [12]: %timeit test_3(my_dict, key_valid)
10000000 loops, best of 3: 151 ns per loop
In [13]: %timeit test_3(my_dict, key_non_valid)
1000000 loops, best of 3: 1.07 μs per loop
In [14]: %timeit test_4(my_dict, key_valid)
1000000 loops, best of 3: 246 ns per loop
In [15]: %timeit test_4(my_dict, key_non_valid)
10000000 loops, best of 3: 189 ns per loop
Conclusion: construction key in dict
is generally fastest, outperformed only by try except
in case of valid key, because it doesn't perform if
operation.
(note however try except
is significantly slower for invalid keys: therefore, since the whole point is you don't know if key is valid, then given an unknown probability of valid vs. invalid, stick with key in dict
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…