Prevent ObjectSpace.count_objects from allocating extra arrays #13906
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
ObjectSpace.count_objects
could cause an unintended array allocation. It returns a hash like{ :T_ARRAY => 100, :T_STRING => 100, ... }
, so it creates the key symbol (e.g.,:T_STRING
) for the first time. On rare occations, this symbol creation internally allocates a new array for symbol management.This led to a problematic side effect where calling
count_objects
twice in a row could produce inconsistent results: the first call would trigger the hidden array allocation, and the second call would then report an increased count for:T_ARRAY
.This behavior caused test failures in
test/ruby/test_allocation.rb
, which performs a baseline measurement before an operation and then asserts the exact number of new allocations.https://rubyci.s3.amazonaws.com/openbsd-current/ruby-master/log/20250716T053005Z.fail.html.gz
This change resolves the issue by pre-interning all key symbols used by
ObjectSpace.count_objects
before its counting. This eliminates the side effect and ensures the stability of allocation-sensitive tests.