Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size too big - ruby

Tags:

arrays

ruby

I am getting a 'ArgumentError: array size too big' message with the following code:

MAX_NUMBER = 600_000_000
my_array = Array.new(MAX_NUMBER)

Question. What is the max value that the Array.new function takes in Ruby?

like image 529
Prakash Murthy Avatar asked Sep 10 '10 18:09

Prakash Murthy


People also ask

What is array size Ruby?

Ruby | Array length() function Array#length() : length() is a Array class method which returns the number of elements in the array. Syntax: Array.length() Parameter: Array. Return: the number of elements in the array.

Can we change the array size at runtime?

Size of an array If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.


1 Answers

An array with 500 million elements is 2 GiBytes in size, which – depending on the specific OS you are using – is typically the maximum that a process can address. In other words: your array is bigger than your address space.

So, the solutions are obvious: either make the array smaller (by, say, breaking it up in chunks) or make the address space bigger (in Linux, you can patch the kernel to get 3, 3.5 and even 4 GiByte of address space, and of course switching to a 64 bit OS and a 64 bit Ruby implementation(!) would also work).

Alternatively, you need to rethink your approach. Maybe use mmap instead of an array, or something like that. Maybe lazy-load only the parts you need.

like image 194
Jörg W Mittag Avatar answered Sep 30 '22 20:09

Jörg W Mittag