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

Merged
merged 3 commits into from
Feb 5, 2025
Merged

feat: add compact #129

merged 3 commits into from
Feb 5, 2025

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
@be-marc
Copy link
Member

be-marc commented Feb 5, 2025

Thanks!

@be-marc be-marc merged commit 8fbda1c into mlr-org:main Feb 5, 2025
3 checks passed
@m-muecke m-muecke deleted the compact branch February 5, 2025 20:59
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.

2 participants