You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For normal objects, eagerly defining ivars is good to avoid trashing
inline caches. But for subclasses of core types like String, ivars
are stored in a global hash table, hence initializing and accessing
them is rather costly. That cost is even higher if a ractor has been
spawned, because looking up the table will require synchronizing the
entire VM.
Based on the assumption that the overwhelming majority of `SafeBuffer`
instances are never mutated, hence never end up unsafe, we can optimize
by marking the unsafe status rather than the opposite.
This way we save on eagerly allocating the external buffer in the
global ivar table, save from having to free it when the buffer is
collected, and also save from having to lookup the table when
accessing the ivar because the VM is smart enough to see the object
has the default shape, hence doesn't have any ivar.
```ruby
require "bundler/inline"
gemfile do
gem "rails", path: "."
gem "benchmark-ips"
end
require "active_support/all"
Benchmark.ips do |x|
x.report("String#html_safe") { "test".html_safe }
end
```
Before:
```
ruby 3.5.0dev (2025-07-17T14:01:57Z master a46309d19a) +YJIT +PRISM [arm64-darwin24]
Warming up --------------------------------------
String#html_safe 575.727k i/100ms
Calculating -------------------------------------
String#html_safe 6.421M (± 1.6%) i/s (155.75 ns/i) - 32.241M in 5.022802s
```
After:
```
ruby 3.5.0dev (2025-07-17T14:01:57Z master a46309d19a) +YJIT +PRISM [arm64-darwin24]
Warming up --------------------------------------
String#html_safe 1.070M i/100ms
Calculating -------------------------------------
String#html_safe 12.470M (± 0.8%) i/s (80.19 ns/i) - 63.140M in 5.063698s
```
0 commit comments