Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add compact #129

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

feat: add compact #129

wants to merge 3 commits into from

Conversation

m-muecke
Copy link
Member

The following pattern is used in a few places in mlr3 packages: discard(x, is.null). compact() is an optimized function for this. If you prefer the pattern from compact3() more than compact2() I can change that since the performance difference is negible.

Small benchmark:

compact1 <- function(x) Filter(length, x)
compact2 <- function(x) x[as.logical(lengths(x))]
compact3 <- function(x) x[lengths(x) > 0L]

x <- list(1:100, NULL, NULL, NULL, 1:100)
bench::mark(
  compact1(x),
  compact2(x),
  compact3(x),
  mlr3misc::discard(x, is.null),
  iterations = 100
)
#> # A tibble: 4 × 6
#>   expression                         min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>                    <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 compact1(x)                     2.83µs   3.08µs    14038.        0B        0
#> 2 compact2(x)                   492.03ns 573.99ns   117142.        0B        0
#> 3 compact3(x)                   491.97ns 573.99ns   143186.        0B        0
#> 4 mlr3misc::discard(x, is.null)   3.77µs   4.08µs   230836.    1.75MB        0

Created on 2025-01-24 with reprex v2.1.1

For reference the purrr and rlang implementations:

@m-muecke m-muecke requested a review from be-marc January 24, 2025 10:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant