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
Using Enumerable#inject on a Hash forces an allocation of an array each
time Hash#each is called on current CRuby versions. Use Hash#each
directly.
Not as elegant, for sure, but it also doesn't require understanding how
inject/reduce works.
Casual benchmark:
```
require 'active_support/all'
require 'benchmark'
p a = ActiveSupport::Duration.build(2716147)
p a.parts
time = Time.current
pre_alloc = GC.stat(:total_allocated_objects)
puts(Benchmark.measure do
300_000.times do
a.since(time)
end
end)
post_alloc = GC.stat(:total_allocated_objects)
puts "alloced=#{post_alloc - pre_alloc}"
```
```diff
diff --git a/before b/after
--- a/before
+++ b/after
@@ -1,4 +1,4 @@
1 month, 1 day, and 1 second
{:months=>1, :days=>1, :seconds=>1}
- 2.311823 0.032300 2.344123 ( 2.439997)
-alloced=14101243
+ 2.223739 0.038590 2.262329 ( 2.316780)
+alloced=12601105
```
So ~5% speed improvement, ~10% fewer objects.
I found this while profiling allocations in the [lobsters benchmark from
yjit-bench][1].
[1]: https://github.com/Shopify/yjit-bench/tree/main/benchmarks/lobsters
0 commit comments