Skip to content

Optimize MessageBus::Client#allowed? method#385

Merged
davidtaylorhq merged 1 commit intodiscourse:mainfrom
moberegger:moberegger/optimize-client-allowed-method
Apr 8, 2026
Merged

Optimize MessageBus::Client#allowed? method#385
davidtaylorhq merged 1 commit intodiscourse:mainfrom
moberegger:moberegger/optimize-client-allowed-method

Conversation

@moberegger
Copy link
Copy Markdown
Contributor

@moberegger moberegger commented Apr 2, 2026

This was coming up as a memory allocation hotspot in our production profiles, specifically the - operation when calculating group_allowed. Luckily there is a very easy optimization here: simply use intersect?! This performs the same check with zero additional memory allocation.

I ran some benchmarks against the allowed? method. I was expecting this optimization to get diluted in the larger method body, but the results look good.

allowed? now allocates no additional memory

Calculating -------------------------------------
                main    40.000  memsize (     0.000  retained)
                         1.000  objects (     0.000  retained)
                         0.000  strings (     0.000  retained)
           optimized     0.000  memsize (     0.000  retained)
                         0.000  objects (     0.000  retained)
                         0.000  strings (     0.000  retained)

Comparison:
           optimized:          0 allocated
                main:         40 allocated - Infx more

Not only that, it is 1.77x faster!

ruby 4.0.2 (2026-03-17 revision d3da9fec82) +YJIT +PRISM [arm64-darwin25]
Warming up --------------------------------------
                main   558.220k i/100ms
           optimized   967.314k i/100ms
Calculating -------------------------------------
                main      6.551M (± 2.3%) i/s  (152.66 ns/i) -     32.935M in   5.030441s
           optimized     11.626M (± 3.4%) i/s   (86.02 ns/i) -     59.006M in   5.082509s

Comparison:
                main:  6550535.1 i/s
           optimized: 11625658.9 i/s - 1.77x  faster

I would expect the improvement to be more profound in a production scenario because the call sites to the allowed? method both happen in a loop; one iterating over messages, another over subscriptions.

@moberegger moberegger marked this pull request as ready for review April 2, 2026 00:50
@davidtaylorhq davidtaylorhq merged commit 0b18e89 into discourse:main Apr 8, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants