Compares Rcpp
construction of sp::Line
objects either:
- Constructed as
new
objects with slots filled directly, or - Constructed the 'usual' way through filling the
sp
object with data.
In R
terms, these are equivalent to:
library (sp)
# first way
obj <- new ("Line")
slot (obj, "coords") <- some_data
# second way
obj <- sp::Line (coords=some_data)
The actual Rcpp
code constructs SpatialLines
, with reasons for differences be readily seen from the sp source: direct construction of a SpatialLines
object requires an sapply
operation which has to be much slower than filling a new
object, as the following code demonstrates.
First load the following C++
file and necessary R
packages:
Sys.setenv ('PKG_CXXFLAGS'='-std=c++11')
Rcpp::sourceCpp('line-construction.cpp')
Sys.unsetenv ('PKG_CXXFLAGS')
library (microbenchmark)
library (sp)
Then the timing comparison:
mb_new <- microbenchmark ( obj <- line_new (), times=1000L )
tt_new <- formatC (mean (mb_new$time) / 1e6, format="f", digits=2) # in ms
mb_fill <- microbenchmark ( obj <- line_fill (), times=1000L )
tt_fill <- formatC (mean (mb_fill$time) / 1e6, format="f", digits=2)
cat ("construct new vs. direct fill times = ", tt_new, " vs ",
tt_fill, "\n", sep="")
## construct new vs. direct fill times = 0.19 vs 0.96