它慢的真正原因是它没有关注 CJ 的默认使用:当参数向量满足 anyDuplicated(vector) == F 时。
也许其他人使用 CJ 的方式不同,但对于独特的向量,还有改进的余地:
速度比较
Unit: milliseconds
expr min lq median uq max neval
dt1 <- CJ(a, b, c) 2394.38929 2434.75660 2439.14362 2444.66607 2686.41990 100
dt2 <- fastCJ(a, b, c) 18.83701 25.33339 25.51254 25.70966 27.60622 100
Output identical: TRUE
代码
library(microbenchmark)
library(data.table)
repTE <- function(x, times, each) {
rep.int(rep.int(x, times=rep.int(each, times=length(x))), times=times)
}
fastCJ <- function(...) {
l <- lapply(list(...), sort.int, method="quick")
seq_ct <- length(l)
if (seq_ct > 1) {
seq_lens <- vapply(l, length, numeric(1))
tot_len <- prod(seq_lens)
l <-lapply(
seq_len(seq_ct),
function(i) {
if (i==1) {
len <- seq_lens[1]
rep.int(l[[1]], times=rep.int(tot_len/len, len))
} else if (i < seq_ct) {
pre_len <- prod(seq_lens[1:(i - 1)])
repTE(l[[i]], times=pre_len, each=tot_len/pre_len/seq_lens[i])
} else {
rep.int(l[[seq_ct]], times=tot_len/seq_lens[seq_ct])
}
}
)
} else {
tot_len <- length(l[[1]])
}
setattr(l, "row.names", .set_row_names(tot_len))
setattr(l, "class", c("data.table", "data.frame"))
if (is.null(names <- names(seq_list))) {
names <- vector("character", seq_ct)
}
if (any(tt <- names == "")) {
names[tt] <- paste0("V", which(tt))
}
setattr(l, "names", names)
data.table:::settruelength(l, 0L)
l <- alloc.col(l)
setattr(l, "sorted", names(l))
return(l)
}
a <- factor(sample(1:1000, 1000))
b <- sample(letters, 26)
c <- runif(100)
print(microbenchmark( dt1 <- CJ(a, b, c), dt2 <- fastCJ(a, b, c)))
cat("Output identical:", identical(dt1, dt2))