python 文字列置換処理で「replace」と「sub」のパフォーマンスを計測して比較する

python 文字列置換処理で「replace」と「sub」のパフォーマンスを計測して比較する

pythonで、文字列置換処理を「replace」と「sub」のそれぞれで実行したパフォーマンスを計測して比較するコードと結果を記述してます。pythonのバージョンは3.10.0を使用してます。

環境

  • OS windows11 home 64bit
  • python 3.10.0

パフォーマンス計測

「time.perf_counter」を使用して、同じ文字列置換処理で「replace」と「sub」を1000万回実行して、計測した結果を比較してみます。

import time
import re

txt = "he llo wo r ld"
n =  10_000_000

# 計測開始
time_sta = time.perf_counter()

# 処理
for i in range(n):
    result = txt.replace(" ","")
    
# 計測終了
time_end = time.perf_counter()

# 結果表示
result = time_end- time_sta
print(f"replace : {result * 1000:.1f} ms") 

# 計測開始
time_sta = time.perf_counter()

# 処理
for i in range(n):
    result = re.sub(" ","",txt)
    
# 計測終了
time_end = time.perf_counter()

# 結果表示
result = time_end- time_sta
print(f"sub : {result * 1000:.1f} ms") 

実行結果をみると「replace」の方がパフォーマンスは良さそうです。

【1回目】
replace : 8192.0 ms
sub : 78216.9 ms

【2回目】
replace : 8444.6 ms
sub : 74875.6 ms

【3回目】
replace : 7976.8 ms
sub : 77943.0 ms