LoginSignup
8
7

More than 1 year has passed since last update.

Pythonのappendをよりはやく

Last updated at Posted at 2019-07-09

これはなに

Pythonのlistのメソッドの一つであるappendをはやくする話です.
私は "Hello World チョットデキル" 程度なのでよく知られた事実かもしれません.

実行環境

  • Python 3.6.7
  • OS: Windows 10 Home 64bit 1903
  • CPU: Pentium Gold G5400 (2C 4T)
  • RAM: 8GB

実際にやってみる

いつもの

append_test.py
numbers = []

for n in range(10 ** 8):
    numbers.append(n)

# 15.14177393913269[sec]
numbers = []

for n in range(10 ** 7):
    numbers.append(n)

# 1.565068006515503[sec]

はやくする

append_test_opt.py
numbers = []
numbers_append = numbers.append

for n in range(10 ** 8):
    numbers_append(n)

# 11.622382164001465[sec]
numbers = []
numbers_append = numbers.append

for n in range(10 ** 7):
    numbers_append(n)

# 1.0725383758544922[sec]

揺らぎが大きいものの,はやくなります.

なぜはやくなるのか

ご存じの方ぜひご教授頂けると嬉しいです。

【追記】

numbers.append(n) は、変数辞書から numbers を捜し、numbersオブジェクトの中から appendメソッドを取り出し、呼び出します。
numbers_append(n) は、変数辞書から numbers_append を探し出し、呼び出します。
参考: https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...

とコメントにて教えていただきました.ありがとうございます.

8
7
2

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