Vignesh Jayavel
Vignesh Jayavel

Reputation: 994

size occupied by an array of nil

I have an array of nil, say

a = [nil,nil,nil]

what is the size (in bytes) of array a?

I use ruby 1.9.3p484

I tried ObjectSpace.memsize_of() method, but the output is quite confusing.

>> a = [nil,nil,nil]
=> [nil, nil, nil]
>> ObjectSpace.memsize_of(a)
=> 0
>> a = [nil,nil,nil,nil]
=> [nil, nil, nil, nil]
>> ObjectSpace.memsize_of(a)
=> 32
>> a = [nil,nil,nil,nil,nil]
=> [nil, nil, nil, nil, nil]
>> ObjectSpace.memsize_of(a)
=> 40

Upvotes: 1

Views: 159

Answers (1)

lukad
lukad

Reputation: 17873

Arrays with size smaller than or equal to RARRAY_EMBED_LEN_MAX (default is 3) will be embedded to improve performance for small arrays. Basically, an array with 3 items or less will not be allocated on the heap.

This explains the confusing output of your example.

require 'objspace'
(1..10).to_a.each { |i| p [nil] * i, ObjectSpace.memsize_of([nil] * i) }
[nil]
0
[nil, nil]
0
[nil, nil, nil]
0
[nil, nil, nil, nil]
32
[nil, nil, nil, nil, nil]
40
[nil, nil, nil, nil, nil, nil]
48
[nil, nil, nil, nil, nil, nil, nil]
56
[nil, nil, nil, nil, nil, nil, nil, nil]
64
[nil, nil, nil, nil, nil, nil, nil, nil, nil]
72
[nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
80
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note that ObjectSpace.memsize_of(array) will only give you the size of the array object itself excluding its items.

Upvotes: 1

Related Questions