DEV Community

Discussion on: How arrays work the way arrays work

Collapse
 
jeffhappily profile image
Cheah Jer Fei

Yeah I understand that every object in Ruby takes up a fixed size of 40 bytes, was wondering is it possible for it to grow beyond 40 bytes, like too much fields etc 🤔If so, what's gonna happen...

Btw, I saw your snippet gist.github.com/edisonywh/c61b3ab5... , you divided memory by 8 to find memory_in_bytes, but isn't memsize_of returning memory size in bytes?

Thread Thread
 
edisonywh profile image
Edison Yap • Edited

I took to your question and tried to look into it a little, and found some interesting stuffs!

require 'objspace'

class Foo
  attr_reader :string
  def initialize
    @string = 'a' * 10_000
  end
end


instance = Foo.new
string = instance.string

puts "Instance size: #{ObjectSpace.memsize_of(instance)}"
#=> 40
puts "String size: #{ObjectSpace.memsize_of(string)}"
#=> 10041

I don't think the value here matters, but what's really interesting to me is that it looks like the memory allocation for the object and its attributes are separated - I think the object instance would just hold reference to its attribute, thus not necessarily bloating the object itself.

Now I have no idea how this works, because this doesn't seem very efficient for garbage collecting.

P.S: Take what I said with a grain of salt as I don't have much a clue!

And you're right! Looks like I made a mistake in my gist, thanks for pointing out!


Edit:

I was thining, if Ruby objects really only store a reference to another part of the memory (as demonstated with the snippet above), then what happens when the pointers itself grows?

To do that I tried something else, here's the snippet.

require 'objspace'

class Foo
  attr_reader :string
  def initialize
    1000.times do |i|
      instance_variable_set("@a#{i}", i)
    end
  end
end

instance = Foo.new
puts "Foo size: #{ObjectSpace.memsize_of(instance)}"
#=> Foo size: 8904

Surprise surprise, the instance itself is now 8904 bytes! (again, I'm not sure how much the value itself matter here), so it looks like the object does get bloat if your have too much fields/attributes.

Well, thanks for asking great questions! I don't think I have all the full answers, but I had a lot of fun trying :) Hope they answered some of you questions as they did mine too!

Thread Thread
 
jeffhappily profile image
Cheah Jer Fei

Woah that's cool! So object does get expanded when it has too much fields, I wonder why would they still set the 40 bytes upfront 🧐

Thanks for taking your time trying to answer my questions, if you don't mind, maybe we can talk more privately? I always wanted to learn from good people 😝

Thread Thread
 
edisonywh profile image
Edison Yap

Sure! It's always nice to see local talents online, so would definitely love to connect :)

Thread Thread
 
jeffhappily profile image
Cheah Jer Fei

Just added you on fb, or would you prefer other way to connect?