[Rcpp-devel] Initialization through constructor or through assignment?
Dirk Eddelbuettel
edd at debian.org
Fri Oct 21 22:47:20 CEST 2011
On 21 October 2011 at 15:12, Douglas Bates wrote:
| Perhaps this is an indication that I should read some sections of "C++
| Annotations" again. I am trying to remember the pros and cons of
| initializing a class instance in C++ through assignment or through the
| copy constructor. So, for example, if I have a class "foo" and a
| function "bar" that returns a foo. Am I better off writing
|
| foo baz(bar());
|
| or
|
| foo baz = bar();
|
| I have tended to prefer the former, but not for any good reasons, at
| least as far as I can remember.
|
| As a much more trivial example, in C I would write
|
| int one = 1;
|
| but in C++ I tend to write
|
| int one(1);
|
| Any comments one way or the other?
For the C example, I think the compiler optimizes that the right way even if
we write it in a suboptimal way. For the initialization, I will gladly admit
that I do not know either. I always suspect the second 'copy' form is
worse. But when I (trying to be empirical ;-) set up a test, it seems to
win, albeit by a tiny, tiny, tiny margin that may not matter all that much.
R> suppressMessages(require(inline))
R> suppressMessages(require(rbenchmark))
R> suppressMessages(require(microbenchmark))
R>
R> ctrFun <- cxxfunction(signature(xs="numeric"), plugin="Rcpp", body='
+ Rcpp::NumericMatrix x(xs);
+ return R_NilValue;
+ ')
R>
R> cpyFun <- cxxfunction(signature(xs="numeric"), plugin="Rcpp", body='
+ Rcpp::NumericMatrix x = Rcpp::NumericMatrix(xs);
+ return R_NilValue;
+ ')
R>
R> M <- matrix(seq(1.0, 100.0^2, by=1.0), 100, 100)
R> benchmark(ctrFun(M), cpyFun(M), order="relative", replications=1e6)
test replications elapsed relative user.self sys.self user.child sys.child
2 cpyFun(M) 1000000 5.358 1.00000 5.34 0.00 0 0
1 ctrFun(M) 1000000 5.387 1.00541 5.35 0.01 0 0
R> microbenchmark(ctrFun(M), cpyFun(M), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 cpyFun(M) 1211 1314 1358 1426 49533807
2 ctrFun(M) 1202 1301 1346 1415 49842042
R>
Dirk
--
"Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
dark to read." -- Groucho Marx
More information about the Rcpp-devel
mailing list