Skip to content

hardcode choices in match.arg#458

Closed
thomasp85 wants to merge 2 commits intojeroen:masterfrom
thomasp85:perf-match.arg
Closed

hardcode choices in match.arg#458
thomasp85 wants to merge 2 commits intojeroen:masterfrom
thomasp85:perf-match.arg

Conversation

@thomasp85
Copy link
Copy Markdown

During performance benchmarking and profiling of plumber2 I stumbled upon the fact that the majority of time in toJSON() during formatting of smaller data is spend on match.arg() calls. The speed of these calls can be improved 3x by hardcoding the choices vector and avoid the lookup it otherwise performs in the calling environment.

This PR simply hardcodes all the values from the function formals into the relevant match.arg calls

@jeroen
Copy link
Copy Markdown
Owner

jeroen commented Dec 9, 2025

Hmm I'm a bit surprised if duplicating the values gives significant improvement. Can you include a quick example? Are talking about more than like 1 millisecond?

@thomasp85
Copy link
Copy Markdown
Author

foo <- function(x = letters) {
  match.arg(x)
}
bar <- function(x = letters) {
  match.arg(x, letters)
}
bench::mark(foo(), bar())
#> # A tibble: 2 × 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 foo()        2.13µs   2.42µs   293471.    1.92KB     29.4
#> 2 bar()      614.91ns  697.1ns  1090702.        0B      0

Created on 2025-12-09 with reprex v2.1.1

It is not a lot, granted, but there are quite a few calls in there and they stack up. As said, for a simple plumber2 api the json conversion is the biggest sink and the match.arg calls are the biggest part of that. As the change is cosmetic and the improvements are real I figured we might as well have it

@jeroen
Copy link
Copy Markdown
Owner

jeroen commented Dec 9, 2025

We are really talking about microseconds here... Even if we have a nested json object with hundreds of asJSON calls, this won't end up to a single millisecond ? I can hardly imagine this is a noticeable difference in plumber2... not sure if this really justifies duplicating this code...

@thomasp85
Copy link
Copy Markdown
Author

fair - I agree it is small gains but since there were no downsides to this I thought I'd give it a go

@thomasp85 thomasp85 closed this Dec 9, 2025
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