[Rd] Proposed speedup of ifelse

Hugh Parsonage hugh@p@r@on@ge @ending from gm@il@com
Thu May 3 05:58:34 CEST 2018


I propose a patch to ifelse that leverages anyNA(test) to achieve an
improvement in performance. For a test vector of length 10, the change
nearly halves the time taken and for a test of length 1 million, there
is a tenfold increase in speed. Even for small vectors, the
distributions of timings between the old and the proposed ifelse do
not intersect.

The patch does not intend to change the behaviour of ifelse (i.e. it
is intended to be a drop-in replacement). However, the patch
inadvertently corrects what I believe to be a bug in the release
version of ifelse: the documentation says that attributes of test are
kept; however, this is not true unless test is atomic.

  library(Matrix)
  M <- Matrix(-10 + 1:28, 4, 7)
  ifelse(M, 1, 2)

The performance improvement does not rely on this, however; so if
current behaviour in these cases is intended, the patch can be
trivially amended to reflect this.

I've written up a short note detailing the performance improvements
and some unit tests at
https://hughparsonage.github.io/content/post/A-new-ifelse.html


Best

Hugh Parsonage



More information about the R-devel mailing list