0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの辞書を作成する際の `{}` と `dict()` の違いとパフォーマンス比較

Posted at

Pythonのdict()と{}で違いがあるらしいと聞いたので、調べてみました。

{}dict() の違い

  • {}(リテラル)
    リテラルを使用して直接辞書型オブジェクトを作成します。

    my_dict = {}
    
  • dict()(コンストラクター)
    dict クラスのコンストラクターを呼び出して辞書型オブジェクトを作成します。

    my_dict = dict()
    

dict() を使用すると、関数呼び出しのオーバーヘッドが発生するため、{} を使用するよりも実行速度が遅くなります。しかし、関数呼び出しのオーバーヘッドはせいぜいナノ秒オーダーのため、パフォーマンス的には無視できるレベルです。

実行速度の比較

以下のコードで、{}dict() を使用して辞書を作成する際の実行時間を比較しました。
※手元の環境で試したため、実行環境によっては差が出る恐れがあります。

import timeit

# {}を使用して辞書を作成
time_literal = timeit.timeit("my_dict = {}", number=1_000_000)

# dict()を使用して辞書を作成
time_func = timeit.timeit("my_dict = dict()", number=1_000_000)

print(f"{{}}: {time_literal}")
print(f"dict(): {time_func}")

実行結果

{}: 0.026 秒
dict(): 0.045 秒

100万回実行して約0.019秒の差が出ました。1回あたり約19ナノ秒(10^-9 秒)ですね。

結論

関数呼び出しのオーバーヘッドはナノ秒オーダーであるため、通常の開発では dict() を使用してもほぼパフォーマンスには影響がないです。パフォーマンスに非常にシビアな状況でなければ、どちらの方法を使用してもいいと思います。しかし、そもそもこのレベルでパフォーマンスがシビアな場合は、Pythonではなく他の言語を使用したほうがいいと思います。

参考資料

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?