Use && instead of &
To determine if both dice are the same, the move_square()
function uses if statements.
if (is_double[1] & is_double[2] & is_double[3]) {
current <- 11 # Go To Jail - square 11 == Jail
}
The &
operator will always evaluate both its arguments. That is, if you type x & y
, R will always try to work out what x
and y
are. There are some cases where this is inefficient. For example, if x
is FALSE
, then x & y
will always be FALSE
, regardless of the value of y
. Thus, you can save a little processing time by not calculating it. The &&
operator takes advantage of this trick, and doesn't bother to calculate y
if it doesn't make a difference to the overall result.
In this code, if is_double[1]
is FALSE
we don't need to evaluate is_double[2]
or is_double[3]
, so we can get a speedup by swapping &
for &&
.
One thing to note is that &&
only works on single logical values, i.e., logical vectors of length 1 (like you would pass into an if
condition), but &
also works on vectors of length greater than 1.
This is a part of the course
“Writing Efficient R Code”
Exercise instructions
- Create an
improved_move()
function, which is similar tomove()
, but uses&&
. - Using
microbenchmark()
, compareimproved_move()
to the previous versionmove()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Example data
is_double
# Define the previous solution
move <- function(is_double) {
if (is_double[1] & is_double[2] & is_double[3]) {
current <- 11 # Go To Jail
}
}
# Define the improved solution
improved_move <- function(is_double) {
if (is_double[1] ___ is_double[2] ___ is_double[3]) {
current <- 11 # Go To Jail
}
}
# microbenchmark both solutions
# Very occassionally the improved solution is actually a little slower
# This is just random chance
microbenchmark(___, ___, times = 1e5)