(This article was first published on

**Romain Francois, Professional R Enthusiast - Tag - R**, and kindly contributed to R-bloggers)Tony Breyal woke up an old code optimization problem in this blog post, so I figured it was time for an Rcpp based solution

This solutions moves down Henrik Bengtsson's idea (which was at the basis of attempt 10) down to C++. The idea was to call sprintf less than the other solutions to generate the strings "001", "002", "003", ...

We can benchmark this version using the rbenchmark package:

> library(rbenchmark) > n <- 2000 > benchmark( + generateIndex10(n), + generateIndex11(n), + generateIndex12(n), + generateIndex13(n), + generateIndex14(n), + columns = + c("test", "replications", "elapsed", "relative"), + order = "relative", + replications = 20 + ) test replications elapsed relative 5 generateIndex14(n) 20 21.015 1.000000 3 generateIndex12(n) 20 22.034 1.048489 4 generateIndex13(n) 20 23.436 1.115203 2 generateIndex11(n) 20 23.829 1.133904 1 generateIndex10(n) 20 30.580 1.455151 >

To

**leave a comment**for the author, please follow the link and comment on his blog:**Romain Francois, Professional R Enthusiast - Tag - R**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...