I am wrapping a number of R functions in a library (purely for syntax consistency with other systems, not performance or anything else). Something like:
ABS_1 <- function (x) { abs(x) }
ABS_2 <- function (x) { .Primitive("abs")(x) }
And I noticed this:
x <- 1e5
microbenchmark::microbenchmark(abs(x), ABS_1(x), ABS_2(x), times = x)
Unit: nanoseconds
expr min lq mean median uq max neval
abs(x) 0 0 51.100760000065896804 0 0 4464203 1e+05
ABS_1(x) 41 123 142.329860000001815479 123 123 326196 1e+05
ABS_2(x) 287 369 398.285890000000563305 369 369 532426 1e+05
I understand there is overhead when wrapping abs()
, but what explains the performance difference between the two wrapping functions ?
This difference doesn’t seem to scale when computing the function on a vector instead:
n <- 1e5
x <- 1:n
microbenchmark::microbenchmark(abs(x), ABS_1(x), ABS_2(x), times = n)
Unit: microseconds
expr min lq mean median uq max neval
abs(x) 7.626 24.03 51.25 24.68 27.18 59664 1e+05
ABS_1(x) 7.790 24.19 52.38 24.89 27.31 59591 1e+05
ABS_2(x) 8.036 24.48 50.11 25.21 27.55 58694 1e+05
I am simply curious what causes the difference.