Skip to content

Instantly share code, notes, and snippets.

@jimhester
Last active August 29, 2015 14:25
Show Gist options
  • Save jimhester/846c2316bff9a85e7900 to your computer and use it in GitHub Desktop.
Save jimhester/846c2316bff9a85e7900 to your computer and use it in GitHub Desktop.
library(microbenchmark)
a <- sample(letters, 1e6, TRUE)
b <- as.factor(a)
microbenchmark(c <- a[a == "d"],
d <- b[b == "d"],
e <- {
mtch <- match("d", levels(b))
b[as.integer(b) == mtch]
})
## Unit: milliseconds
## expr
## c <- a[a == "d"]
## d <- b[b == "d"]
## e <- { mtch <- match("d", levels(b)) b[as.integer(b) == mtch] }
## min lq mean median uq max neval cld
## 19.685260 19.747577 20.588849 19.836498 20.275723 27.79781 100 b
## 43.150390 43.381784 45.982250 43.683979 48.716526 70.98689 100 c
## 4.003705 4.106672 4.466901 4.149938 4.223226 12.29115 100 a
all.equal(c, as.character(d), as.character(e))
## [1] TRUE
object.size(a)
## 8001288 bytes
object.size(b)
## 4001856 bytes
object.size(as.integer(b))
## 4000040 bytes
object.size(c)
## 308216 bytes
object.size(d)
## 155920 bytes
object.size(e)
## 155920 bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment