Viktor
Viktor

Reputation: 472

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

Consider the code:

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

Running this code I see better performance of order() compared to sort.list(). On the other hand, if I use a sample size of 100000 the performance of both functions is nearly the same.

Why does it happen?

Upvotes: 0

Views: 298

Answers (1)

J.R.
J.R.

Reputation: 3888

Take a look at the function sort.list(), it calls order() ie. they will be the same when this part amounts to the time-intensive part (large vector):

> 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))
}

Upvotes: 6

Related Questions