Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency/comparison of sprintf vs paste0

Tags:

r

I know paste() and paste0() are extremely popular in R, but I find myself often using sprintf() when I want to build a long string with some variables.

For example

x <- "a"
y <- 10
paste0("The value of x is ", x, " and y is ", y, ".")
sprintf("The value of x is %s and y is %d.", x, y)

I find the sprintf() version much easier to write and the code less clunky. I couldn't find any discussion of the benefits of one over the other. Is there any reason for me not to use sprintf() when the basic functionality of paste is all I need? (if I need to use the collapse or sep arguments then obviously sprintf() will not do).

The only thing I can think of is that maybe sprintf() is slower because it checks that the types match.

like image 430
DeanAttali Avatar asked Feb 01 '15 03:02

DeanAttali


1 Answers

One reason I could think of to use paste0 or paste instead of sprintf is that you don't need to think about the types of arguments being passed.

In terms of efficiency, sprintf appears to have an edge, at least on the example you gave and my machine:

library(microbenchmark)
microbenchmark(paste0("The value of x is ", x, " and y is ", y, "."),
               sprintf("The value of x is %s and y is %d.", x, y))
# Unit: microseconds
#                                                   expr   min     lq    mean median     uq    max neval
#  paste0("The value of x is ", x, " and y is ", y, ".") 2.924 3.0185 3.45632 3.0950 3.1575 36.421   100
#     sprintf("The value of x is %s and y is %d.", x, y) 1.328 1.4130 1.54794 1.4535 1.5430  7.513   100
like image 107
josliber Avatar answered Nov 16 '22 02:11

josliber