Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiplying elements of list with lapply is almost twice as fast with in-line function definition than with standard "*"

If we want to multiply of elements of a list by a constant, we can do so with lapply. However, I have observed that defining the function to be applied in-line is almost twice faster than specifying "*" as the function to be applied:

library(microbenchmark)
microbenchmark::microbenchmark(x=lapply(X=list(a=c(1,2,3)), FUN=function(x) x*1000), y=lapply(X=list(a=c(1,2,3)), "*", 1000), times = 10000)

This gives me a median of around 1100 nanoseconds for the first expression, and around 1900 nanoseconds for the second one.

Any ideas why this could be happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

lapply calls match.fun, which must spend some time matching the string "*" to the primitive function `*`. Passing the function directly avoids the overhead.

l <- list(1, 2, 3)
microbenchmark::microbenchmark(lapply(l, function(x) x * 1000),
                               lapply(l, "*", 1000),
                               lapply(l, `*`, 1000),
                               times = 1e+06L)
## Unit: nanoseconds
##                             expr  min   lq     mean median   uq      max neval
##  lapply(l, function(x) x * 1000) 1271 1435 1614.497   1476 1517  1243981 1e+06
##             lapply(l, "*", 1000) 1640 1763 2026.791   1804 1886 16498605 1e+06
##             lapply(l, `*`, 1000)  861  984 1198.956   1025 1066 16636365 1e+06
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading