2016-10-07 11 views
1

str_replace_allの実行でパフォーマンスの差異が発生するかどうかは疑問です。例えばパフォーマンスの比較stringr - str_replace_all

text <- c("a","b", "c") 
str_replace_all(text, c("a", "b", "c"), c("d", "e", "f")) 

str_replace_all(text, "a", "d") 
str_replace_all(text, "b", "e") 
str_replace_all(text, "c", "f") 

どちらも私に同じ結果を得るが、私は近い20万の文書にしている場合と同じ手順をしていた場合より速いだろうかと思いました。各ドキュメントファイルは長くなっていますか?

+0

ほとんどの場合パフォーマンスの質問では、答えは「依存している」、「問題が発生するまで心配しないでください」です。本当の答えは「テストする」ことです。 –

答えて

0

textの値を変更する必要がないため、単一のstr_replace_allコールでパフォーマンスが向上することは明らかです。たとえば、str_replace_allに電話してtextの値を変更する必要がある場合は、交換するたびに値を再割り当てする必要があります。これは追加のオーバーヘッドを意味します。ここで

は、3つの機能を持つテストです:f1は、最初のアプローチを使用していますf2が第二を使用し、f3f2の単なる「連鎖」バージョンです:times = 50000

> library(microbenchmark) 
> text <- c("a", "b", "c") 

> f1 <- function(text) { text=str_replace_all(text, "a", "d"); text = str_replace_all(text, "b", "e"); text=str_replace_all(text, "c", "f"); return(text) } 
> f1(text) 
[1] "d" "e" "f" 
> f2 <- function(text) { return(str_replace_all(text, c("a", "b", "c"), c("d", "e", "f"))) } 
> f2(text) 
[1] "d" "e" "f" 
> f3 <- function(text) { return(str_replace_all(str_replace_all(str_replace_all(text, "c", "f"), "b", "e"), "a", "d")) } 
> f3(text) 
[1] "d" "e" "f" 
> test <- microbenchmark(f1(text), f2(text), f3(text), times = 50000) 
> test 
Unit: microseconds 
    expr  min  lq  mean median  uq  max neval 
f1(text) 225.788 233.335 257.2998 239.673 262.313 25071.76 50000 
f2(text) 182.321 187.755 207.1858 191.980 210.393 24844.76 50000 
f3(text) 224.581 231.825 255.2167 237.863 259.898 24531.74 50000 

、関数は50,000回実行し、そしてメジアン値は、低い四分位(LQ)と上位四分位点(UQ)値とともに、f2と最低である、証明単一そのが最も速いです。 enter image description here

をそして最後に、それはあなたが唯一のリテラル文字列を交換する必要がある場合stri_replace_all_fixed stringi からパッケージを使用するのが最善です:autoplot(test)は(ggplot2ライブラリから)を示しています。次に、ベンチマークがあります:

> library(stringi) 
> f1 <- function(text) { text=stri_replace_all_fixed(text, "a", "d"); text = stri_replace_all_fixed(text, "b", "e"); text=stri_replace_all_fixed(text, "c", "f"); return(text) } 
> f2 <- function(text) { return(stri_replace_all_fixed(text, c("a", "b", "c"), c("d", "e", "f"))) } 
> f3 <- function(text) { return(stri_replace_all_fixed(stri_replace_all_fixed(stri_replace_all_fixed(text, "c", "f"), "b", "e"), "a", "d")) } 
> test <- microbenchmark(f1(text), f2(text), f3(text), times = 50000) 
> test 
Unit: microseconds 
    expr min lq  mean median uq  max neval cld 
f1(text) 7.547 7.849 9.197490 8.151 8.453 1008.800 50000 b 
f2(text) 3.321 3.623 4.420453 3.925 3.925 2053.821 50000 a 
f3(text) 7.245 7.547 9.802766 7.849 8.151 50816.654 50000 b 
関連する問題