Last active
June 8, 2018 19:56
-
-
Save wch/9fca93ab0e2b7b690691 to your computer and use it in GitHub Desktop.
car, cdr, and push for pairlists in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(inline) | |
library(microbenchmark) | |
car <- cfunction(c(x = "pairlist"), ' | |
if (x == R_NilValue) | |
return R_NilValue; | |
if (TYPEOF(x) != LISTSXP) | |
error("x must be a pairlist"); | |
return CAR(x); | |
') | |
cdr <- cfunction(c(x = "pairlist"), ' | |
if (x == R_NilValue) | |
return R_NilValue; | |
if (TYPEOF(x) != LISTSXP) | |
error("x must be a pairlist"); | |
return CDR(x); | |
') | |
push <- cfunction(c(x = "pairlist", value = 'ANY'), ' | |
if (x != R_NilValue && TYPEOF(x) != LISTSXP) | |
error("x must be a pairlist"); | |
return CONS(value, x); | |
') | |
n <- 1e4 | |
l <- as.list(1:n) | |
p <- as.pairlist(1:n) | |
microbenchmark( | |
# Get head item | |
z <- l[[1]], | |
z <- p[[1]], | |
z <- car(p), | |
# Add to head | |
z <- c(1, l), | |
z <- c(1, p), | |
z <- push(p, 1), | |
# Add to tail | |
z <- c(l, 1), | |
z <- c(p, 1), | |
# Remove from head | |
z <- l[-1], | |
z <- p[-1], | |
z <- cdr(p), | |
# Remove from tail | |
z <- l[seq_len(length(l) - 1)], | |
z <- p[seq_len(length(p) - 1)], | |
unit = "us" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any where you post the benchmark result?