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?

Filter関数とリスト内包表記の動作速度の違い

Last updated at Posted at 2024-06-26

やっぱり基礎が大事ということで、基礎本を読んでいたところ
「高階関数のmap関数やfilter関数を使うより、リスト内包を使った方が速い」との事。

どのぐらい違うか試してみた。

ランダムに大量の配列を作成

import random

# ランダムに配列を作成
array = [random.randint(0, 10000000) for _ in range(10000000)]

filter()を使って計測

処理は偶数値のみ抽出

import time

start = time.time()
list(filter(lambda n: n % 2 == 0, array))
end = time.time()
filtertime = end - start
print("filter time: ", filtertime)

> filter time:  0.48375964164733887

リスト内包を使って計測

import time

start = time.time()
[n for n in array if n % 2 == 0]
end = time.time()
connotationtime = end - start
print("list time: ", connotationtime)

> list time:  0.35934996604919434

結果

filter time:  0.48375964164733887
list time:  0.35934996604919434
Time difference : 0.12440967559814453

1.35倍ほど早くなっていた。
※map関数を使用した場合もほぼ同じぐらいの差があった。

filter関数はlambdaを呼び出して処理を行っている為どうも遅いらしい。
lambdaではなく関数を使用しても結果同じことなので、リスト内包を使用したほうが効率的!!

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?