为什么 order() 比 sort.list() 快?

Why is order() faster than sort.list()?

考虑代码:

a=runif(1000)
microbenchmark::microbenchmark(order(a,method="radix"))
microbenchmark::microbenchmark(sort.list(a,method="radix"))

运行 与 sort.list() 相比,我发现 order() 的性能更好。另一方面,如果我使用 100000 的样本大小,则两个函数的性能几乎相同。

为什么会这样?

看看函数 sort.list(),它调用 order() 即。当这部分相当于时间密集部分(大向量)时,它们将是相同的:

> base::sort.list
function (x, partial = NULL, na.last = TRUE, decreasing = FALSE, 
    method = c("shell", "quick", "radix")) 
{
    if (is.integer(x) || is.factor(x)) 
        method <- "radix"
    method <- match.arg(method)
    if (!is.atomic(x)) 
        stop("'x' must be atomic for 'sort.list'\nHave you called 'sort' on a list?")
    if (!is.null(partial)) 
        .NotYetUsed("partial != NULL")
    if (method == "quick") {
        if (is.factor(x)) 
            x <- as.integer(x)
        if (is.numeric(x)) 
            return(sort(x, na.last = na.last, decreasing = decreasing, 
                method = "quick", index.return = TRUE)$ix)
        else stop("method = \"quick\" is only for numeric 'x'")
    }
    if (is.na(na.last)) {
        x <- x[!is.na(x)]
        na.last <- TRUE
    }
    if (method == "radix") {
        return(order(x, na.last = na.last, decreasing = decreasing, 
            method = "radix"))
    }
    .Internal(order(na.last, decreasing, x))
}