값을 변경할 필요가 없으므로 str_replace_all
단일 통화로 더 나은 성능을 발휘할 수 있습니다. 자, str_replace_all
으로 전화하여 text
값을 변경해야 할 때마다 교체 할 때마다 값을 다시 지정해야하므로 추가 오버 헤드가 발생합니다. f2
번째 사용하고 f3
단지 f2
의 "체인화"버전이고, f1
첫 번째 접근 방식을 사용한다 : 상기 함수는 50,000 번 수행 하였다 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
여기
3 개 기능 테스트입니다 상기
중간 값,
하부 분위 (LQ) 및 상부
분위 (UQ) 값과 함께,
f2
와 최저 인, 증명 한그이 가장 빠릅니다.
을 그리고 마지막으로, 당신은 리터럴 문자열을 교체해야하는 경우 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
성능 질문에서 항상 그렇듯이 답변은 "의존적"이며 "문제가 발생할 때까지는 걱정하지 마십시오."입니다. 진짜 대답은 "시험해보십시오"입니다. –