Claire
Claire

Reputation: 33

Does the size of the objects in a Ruby array contribute to the memory usage of the array itself?

I have a set of variables foo, bar,... (the number of variables can vary from 10 to a few hundreds) that I need to access in a loop. Thus I'd like to add them in an array. The problem is that those variables are quite big.

If I create an array a = [foo, bar, ...] what will be the impact on memory usage? What will be the memory size of a? Will it be the size of foo + the size of bar + ...? I'm not sure if the "pass-by-value" of ruby has an impact here.

I could do a = ['foo', 'bar', ...] but I would then have to use eval and I'd like to avoid that.

Upvotes: 2

Views: 165

Answers (1)

user513951
user513951

Reputation: 13612

In MRI Ruby, an array does not copy and contain the values of all the objects inside it. The array contains a series of pointers in memory. So the size of an array is the size of the struct necessary for the array's internal pieces (e.g. capacity, length), plus the size of one pointer (a void*, so 4 bytes on a 32-bit architecture) per object in the array. The objects in the array occupy their own memory space elsewhere.

Upvotes: 1

Related Questions