This small benchmark compares the
performance of the base64 encoding/decoding in package
base64url
with the implementations in the packages base64enc
and openssl
.
## Linking to: OpenSSL 3.0.13 30 Jan 2024
library(microbenchmark)
x = "plain text"
microbenchmark(
base64url = base64_urlencode(x),
base64enc = base64encode(charToRaw(x)),
openssl = base64_encode(x)
)
## Unit: nanoseconds
## expr min lq mean median uq max neval
## base64url 541 601.0 894.78 711.5 801 19406 100
## base64enc 1503 1653.5 3629.49 1884.0 2034 176358 100
## openssl 13966 14466.0 16291.84 14757.5 15214 144700 100
x = "N0JBLlRaUTp1bi5KOW4xWStNWEJoLHRQaDZ3"
microbenchmark(
base64url = base64_urldecode(x),
base64enc = rawToChar(base64decode(x)),
openssl = rawToChar(base64_decode(x))
)
## Unit: nanoseconds
## expr min lq mean median uq max neval
## base64url 561 631 953.77 782 867.0 19276 100
## base64enc 1893 2104 3068.45 2414 2644.5 69329 100
## openssl 20959 21700 24043.87 22096 22577.0 155160 100
Here, the task has changed from encoding/decoding a single string to
processing multiple strings stored inside a character vector. First, we
create a small utility function which returns n
random
strings with a random number of characters (between 1 and 32) each.
rand = function(n, min = 1, max = 32) {
chars = c(letters, LETTERS, as.character(0:9), c(".", ":", ",", "+", "-", "*", "/"))
replicate(n, paste0(sample(chars, sample(min:max, 1), replace = TRUE), collapse = ""))
}
set.seed(1)
rand(10)
## [1] "*MaHQn6Yu1gKKHRGIPLtBtRNR" "MYPfxFnbSrv,mNVwCmvBVGSuE"
## [3] "qV:7YH" "aQ6zo5CxPV"
## [5] "Mx0NIQaCvBK8T-YRW73WX" "gtxY0pbV,R+sqHEITspNiXx"
## [7] "FMKlnpob,-" "qeOEJWOC:a040XDbJNK3AOo4"
## [9] "9fdI4y" "KB9tCP7,BElRzGd0xKon03XtbcLoB2/"
Only base64url
is vectorized for string input, the
alternative implementations need wrappers to process character
vectors:
base64enc_encode = function(x) {
vapply(x, function(x) base64encode(charToRaw(x)), NA_character_, USE.NAMES = FALSE)
}
openssl_encode = function(x) {
vapply(x, function(x) base64_encode(x), NA_character_, USE.NAMES = FALSE)
}
base64enc_decode = function(x) {
vapply(x, function(x) rawToChar(base64decode(x)), NA_character_, USE.NAMES = FALSE)
}
openssl_decode = function(x) {
vapply(x, function(x) rawToChar(base64_decode(x)), NA_character_, USE.NAMES = FALSE)
}
The following benchmark measures the runtime to encode 1000 random strings and then decode them again:
set.seed(1)
x = rand(1000)
microbenchmark(
base64url = base64_urldecode(base64_urlencode(x)),
base64enc = base64enc_decode(base64enc_encode(x)),
openssl = openssl_decode(openssl_encode(x))
)
## Unit: microseconds
## expr min lq mean median uq max neval
## base64url 204.491 217.4445 236.7282 233.8255 242.126 527.182 100
## base64enc 4690.610 4779.0140 5543.2551 4850.9335 4958.293 44182.261 100
## openssl 37450.427 38567.2045 38982.0700 38867.8290 39229.728 43197.516 100