あらすじ
テストとかで dict たくさん作るときあるけど、どっちのほうがきれいに書けるかなーっておもったので、
実際に計測してみた。(ひまじんか)
縦に書くか、横に書くか、さあどうなるか。。
実行環境
paiza.io にて python3 を指定
結果
方法1
.py
import time
time_list = []
for times in range(100):
start = time.time()
a={}
for i in range(10000):
keys = [('customer{}'.format(i), '田中たろう'), ('phone_number{}'.format(i),'080-1111-2222'), ('order_number{}'.format(i), '0123456789')]
tmp = dict(keys)
a.update(tmp)
elapsed_time = time.time() - start
time_list.append(elapsed_time)
print(sum(time_list)/100)
# 0.015053222179412842
方法2
.py
import time
time_list2 = []
for times in range(100):
start = time.time()
a = {}
for i in range(10000):
tmp = {}
tmp['customer{}'.format(i)] = '田中たろう'
tmp['phone_number{}'.format(i)] = '080-1111-2222'
tmp['order_number{}'.format(i)] = '0123456789'
a.update(tmp)
elapsed_time = time.time() - start
time_list2.append(elapsed_time)
print(sum(time_list2)/100)
# 0.011392412185668945
何回やってもかかる時間は 方法1 > 方法2
でした。
まとめ
方法2のほうが行数かかるけど見やすいし早いからいっか!