This small benchmark compares the performance of the base64 encoding/decoding in package base64url
with the implementations in the packages base64enc
and openssl
.
library(base64url)
library(base64enc)
library(openssl)
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 cld
## base64url 512 590.5 971.53 769.0 884.5 19845 100 a
## base64enc 1074 1245.0 108005.33 1647.5 1823.5 10529387 100 a
## openssl 12793 13099.5 15090.23 13359.5 13767.0 97667 100 a
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 cld
## base64url 493 577 929.30 726.5 1035.5 13151 100 a
## base64enc 3381 3585 4843.14 4236.0 4561.5 70327 100 b
## openssl 19140 19594 21121.08 19912.0 20212.0 102854 100 c
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] "zN.n9+TRe" "mVA1IX/"
## [3] "1,oSisAaA8xHP" "m5U2hXC4S2MK2bGY"
## [5] "G7EqegvJTC.uFwSrH0f8x5x" "G97A1-DXBw0"
## [7] "XiqjqeS" "13FC3PTys/RoiG:P*YyDkaXhES/IH"
## [9] "0FJopP" "fcS,PMK*JVPqrYFmZh7"
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
## base64url 192.792 199.242 233.7204 226.315 259.414 387.039
## base64enc 5490.085 5641.812 5921.4435 5700.369 6048.102 8864.857
## openssl 32889.338 33628.666 35417.5657 34204.795 35348.879 119960.617
## neval cld
## 100 a
## 100 b
## 100 c