Skip to content

Recommend !is.unsorted() instead of identical(x, sort(x)) in sort_linter() #2908

@Bisaloo

Description

@Bisaloo

Not a super common pattern:

https://github.com/search?q=language%3AR+%2Fidentical%5C%28%5Cw%2B%2C+sort%5C%28%5Cw%2B%5C%29%5C%29%2F&type=code

But there is a huge opportunity for optimization here:

x <- runif(1e5)

microbenchmark::microbenchmark(
  identical(x, sort(x)),
  !is.unsorted(x),
  check = "identical"
)
#> Unit: microseconds
#>                   expr      min       lq       mean   median       uq      max
#>  identical(x, sort(x)) 4010.383 4313.883 4636.98955 4496.855 4761.682 7040.232
#>        !is.unsorted(x)   40.104   41.166   46.29157   42.666   46.807   86.509
#>  neval
#>    100
#>    100

x <- sort(x)

microbenchmark::microbenchmark(
  identical(x, sort(x)),
  !is.unsorted(x),
  check = "identical"
)
#> Unit: nanoseconds
#>                   expr  min     lq    mean median     uq   max neval
#>  identical(x, sort(x)) 3612 3732.0 4094.85 3872.5 4033.0 22994   100
#>        !is.unsorted(x)  662  722.5  803.60  773.0  800.5  3131   100

Created on 2025-07-30 with reprex v2.1.1

Should probably not lint if na.last = TRUE or FALSE or decreasing = TRUE in sort().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions