0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

dict ってどう作るのが早いの?

Posted at

あらすじ

テストとかで 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のほうが行数かかるけど見やすいし早いからいっか!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?