Pregunta

Can anyone help me understand why an object of Float doesn't have a fixed object_id while an object of Fixnum has a fixed object-id?

C:\>ruby -v
ruby 2.0.0p0 (2013-02-24) [i386-mingw32]

C:\>irb --simple-prompt
DL is deprecated, please use Fiddle
>> 10.object_id
#=> 21
>> 10.object_id
#=> 21
>> 10.22.object_id
#=> 18272628
>> 10.22.object_id
#=> 15089952
>> 3.14.object_id
#=> 18577176
>> 3.14.object_id
#=> 16707660
¿Fue útil?

Solución

In Ruby 1.8 & 1.9, floats are never immediates, so all floats require a new memory allocation.

In Ruby 2.0.0, on 64 bit systems, many floats are now immediates. This means that the typical floats don't require memory allocation & deallocation anymore, so much faster operations.

Ruby stores its values in a pointer (32 or 64 bits, depending on the platform). It actually uses a trick to store immediates in that pointer. This is the reason why Fixnum can only hold 31 / 63 bits.

On 32 bit platforms, there's no clever way to store floats, but on 64 bits platforms, it's possible to use the first ones to flag this value as an immediate float and the remaining 60 or so to hold the data. The floats that do require the full 64 bits can not be immediates, though, so these are stored like before using an actual pointer.

More info on this optimization can be found in the original feature request.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top