rhai icon indicating copy to clipboard operation
rhai copied to clipboard

Optimize Script and Method Calls

Open djgaven588 opened this issue 4 months ago • 4 comments

A bit ago I spent some time optimizing Rhai for my project.

These changes helped out a lot for my use case, and are mostly focused on calling lots of scripts, and those scripts calling lots of methods.

Most of these changes involve reducing function calls (map_or_else for instance), using hashbrown always, or preventing excessive iteration (drains).

djgaven588 avatar Sep 06 '25 21:09 djgaven588

Thanks for the contribution! There seem to be conflicts. Can you resolve them?

schungx avatar Sep 07 '25 02:09 schungx

Also, I see that you have replaced map_or etc. with if let, and replaced iterators with for loops. Theoretically speaking, these two styles should compile down to very similar machine codes, under release builds with LTO. For example, map_or etc. are usually inlined and then turned into essentially if let. Most iterators are replaced with their equivalent implementation of for loops. That's what I found most when doing Rust.

Do you have benchmarks to show clear improvements in runtime?

Also can you elaborate a bit on what you intend to do with hashbrown?

schungx avatar Sep 07 '25 02:09 schungx

Need to set aside some time to circle back to this, but yes I can resolve them as well as clean up the PR a bit when I do some performance comparisons.

In the experience I had when optimizing it, I found that replacing things such as map_or reduced function calls. I just have a regular release build, so I'm unsure of the impacts of LTO settings (they default to thin I think, which seems reasonable).

For hashbrown, the goal is to use it over the std hashmap and hashset, as it is dramatically faster.

djgaven588 avatar Sep 11 '25 08:09 djgaven588

In the experience I had when optimizing it, I found that replacing things such as map_or reduced function calls. I just have a regular release build, so I'm unsure of the impacts of LTO settings (they default to thin I think, which seems reasonable).

Then I would strongly suggest you try with a full LTO build. Sometimes Rust would not inline across crate boundaries and LTO forces it to do so, resulting in drastically reduced code. I never have release builds without LTO these days.

For hashbrown, the goal is to use it over the std hashmap and hashset, as it is dramatically faster.

I have heard similar but it seems the Rust standard hashmap is the hashbrown one for std builds. And Rhai already uses a fast hashing implementation so I won't expect performance to differ.

I would appreciate some benchmarks.

schungx avatar Sep 11 '25 13:09 schungx