詳解Python字典查找性能

timeit.repeat

timeit.repeat默認會執行3輪,每輪執行1000000次。返回每輪的總執行時間列表

字典獲取性能

大傢都知道字典獲取分為

中括號獲取,獲取不到會拋出KeyError

get獲取,獲取不到會返回默認值

下面比較兩種獲取方式的性能

數據準備

一條簡單一條復雜

# logging標準庫的level字典
level_mapping = {'CRITICAL': 50, 'FATAL': 50, 'ERROR': 40, 'WARN': 30, 'WARNING': 30, 'INFO': 20, 'DEBUG': 10, 'NOTSET': 0}
# elasticsearch日志
record = {'_index': 'logstash-project.test-env.release-user.root-2021', '_type': 'doc', '_id': '2f60jn0BaH-cdSPUSkiF', '_version': 1, '_score': None, '_source': {'method': 'GET', 'index_name': 'project.test-env.release-user.root', '@version': 'flask', 'path': 'D:\\alpha\\flask\\logstash\\core\\flask.py', 'logger_name': 'flask.exception', 'stack_info': None, 'user': 'root', '@timestamp': '2021-12-06T07:45:20.056Z', 'level': 'ERROR', 'thread_name': 'Thread-5', 'type': 'exception', 'env': 'release', 'process': 8716, 'funcName': 'exceptions', 'port': 55792, 'project': 'test', 'tags': [], 'lineno': 89, 'request': {'headers': {'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Postman-Token': '359faa6e-9527-4de7-82ff-eecb92656875', 'User-Agent': 'PostmanRuntime/7.28.4', 'Cookie': 'csrftoken=bf58fmaG5wBVabJwBeD8srVsfw7EjKe0VN7xD8mu817UzVm', 'Accept': '*/*', 'Host': '127.0.0.1:5000'}, 'args': {'a': '11', 'b': '22'}}, 'message': 'division by zero', 'host': 'DESKTOP-JCQ9527', 'status_code': 500, 'stack_trace': 'Traceback (most recent call last):\n  File "D:\\Envs\\logstash\\lib\\site-packages\\flask\\app.py", line 1950, in full_dispatch_request\n    rv = self.dispatch_request()\n  File "D:\\Envs\\logstash\\lib\\site-packages\\flask\\app.py", line 1936, in dispatch_request\n    return self.view_functions[rule.endpoint](**req.view_args)\n  File "D:\\flask\\logstash\\app.py", line 112, in get_raise\n    a/0\nZeroDivisionError: division by zero\n', 'remote_addr': '127.0.0.1', 'url': 'http://127.0.0.1:5000/raise?a=11&b=22'}, 'fields': {'@timestamp': ['2021-12-06T07:45:20.056Z']}, 'sort': [1638776720056]}
def test():
    level_mapping['CRITICAL']
timeit.repeat(lambda: test())
[0.08700739999994767, 0.0864886999997907, 0.08675769999990735]
# 中括號加try except
def test1():
    try:
        level_mapping['CRITICA']
    except:
        pass
timeit.repeat(lambda: test1())
[0.09164779999991879, 0.0921809999999823, 0.09076550000099814]  # key存在
[0.17694680000022345, 0.1759290999998484, 0.17659119999916584]  # key不存在
def test2():
    level_mapping.get('CRITICAL') 
timeit.repeat(lambda: test2())
[0.131671400000414, 0.12985489999982747, 0.13035420000005615]

中括號獲取比get方式快瞭50%左右;

但當使用中括號加try except,key不存在時要慢近一倍;

使用get時key存不存在設不設默認值都一樣。

復雜獲取

def test3():
    level_mapping[record['_source']['level']]
timeit.repeat(lambda: test3())
[0.1141027999999551, 0.11351319999994303, 0.11431539999989582]
def test4():
    level_mapping.get(record.get('_source').get('level'))
timeit.repeat(lambda: test4())
[0.22142400000007, 0.21937850000017534, 0.21913369999992938]

隨著數據的復雜嵌套和鏈式操作,這次快瞭整整一倍。

總結

在能非常確定key存在且頻繁獲取數據的情況下,應該盡量使用中括號取值。

另外在Python3.6後,重寫瞭字典的底層數據結構,從而使字典變得有序。

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: