Project

General

Profile

Actions

Bug #22290

closed

Adding instance variables to anonymous object may bloat all future classes

Bug #22290: Adding instance variables to anonymous object may bloat all future classes
1

Added by byroot (Jean Boussier) 3 days ago. Updated 1 day ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:126564]

Description

Reproduction script:

o = Object.new
10.times do |i|
  o.instance_variable_set("@a_#{i}", 1)
end

class Test
  def initialize(a, b)
    @a = a
    @b = b
  end
end

require 'objspace'
p ObjectSpace.memsize_of(Test.new(1, 2))

Expected:

40 # or 32 on 4.1.dev

Actual:

160

Explanation

Class records the max number of instance variables any of its instances held (max_iv_count).
When inheriting from a class, max_iv_count is copied in the child class.

If you add instance variables to an instance of Object, any future direct children of Object will start with a larger than needed max_iv_count and will cause Ruby to potentially allocate much larger objects than needed.

All versions since 3.2 are affected, the issue was fixed on master a couple months.

I believe we should backport the fix (I'm working on it), because otherwise some un-proper code running early in the process life-cycle can cause significant memory waste.

Actions

Also available in: PDF Atom