Skip to content

Use matrix operations where appropriate - #13

Merged
EricMarcon merged 5 commits into
EricMarcon:masterfrom
Bisaloo:performance
Aug 4, 2026
Merged

Use matrix operations where appropriate#13
EricMarcon merged 5 commits into
EricMarcon:masterfrom
Bisaloo:performance

Conversation

@Bisaloo

@Bisaloo Bisaloo commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

For better performance

x <- matrix(
  runif(1e6),
  1000,
  1000
)

bench::mark(
  rowMeans(x),
  apply(x, 1, mean),
  iterations = 100
)
#> # A tibble: 2 × 6
#>   expression             min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>        <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 rowMeans(x)         2.92ms   2.98ms     334.     28.7KB       0 
#> 2 apply(x, 1, mean)   9.74ms  10.25ms      90.3    19.2MB     168.

bench::mark(
  tcrossprod(x),
  x %*% t(x),
  iterations = 100
)
#> # A tibble: 2 × 6
#>   expression         min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>    <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 tcrossprod(x)   9.39ms   12.5ms      74.2    7.63MB     24.7
#> 2 x %*% t(x)     22.42ms   26.9ms      34.9   15.26MB     28.6

df <- as.data.frame(x)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

bench::mark(
  df / 100,
  mutate(df, across(everything(), ~ .x / 100)),
  iterations = 100
)
#> Warning: Some expressions had a GC in every iteration; so filtering is
#> disabled.
#> # A tibble: 2 × 6
#>   expression                             min median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>                          <bch:> <bch:>     <dbl> <bch:byt>    <dbl>
#> 1 df/100                                25ms 28.2ms      33.3    8.13MB     33.3
#> 2 mutate(df, across(everything(), ~.… 42.7ms 62.4ms      15.7    14.8MB     22.6

Created on 2026-07-31 with reprex v2.1.1

Some of these changes are not completely trivial and I hope I didn't mess anything up. Please double check.

Related to openjournals/joss-reviews#10860.

@EricMarcon
EricMarcon merged commit c9675a1 into EricMarcon:master Aug 4, 2026
0 of 2 checks passed
@EricMarcon

Copy link
Copy Markdown
Owner

Thanks.
In commit 730026d, the division returns a data.frame when a tibble is needed. I'll add as_tibble() after merging.

EricMarcon added a commit that referenced this pull request Aug 4, 2026
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