Robert Klemme
7/1/2005 9:08:00 PM
Eustaquio Rangel de Oliveira Jr. <eustaquiorangel@yahoo.com> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi.
>
> I'm wondering here how and where Fixnum are created.
> I saw that ObjectSpace does not returns immediate values, ok, I was
> curious about why having
>
> n1, n2, n3, n4 = 1, 2, 3, 1
>
> was returning nothing there on ObjectSpace.each_object(Fixnum).
> I know that Fixnum are immediate values, and "they are assigned or
> passed as parameters, the actual object is passed, rather than a
> reference to that object.".
>
> But reading about "There is effectively only one Fixnum object
> instance for any given integer value, so, for example, you cannot add
> a singleton method to a Fixnum.", my doubt is if "the actual object"
> and "only one Fixnum object instance" referenced above is:
>
> 1 - A object created for each Fixnum (like o1 for n1 AND n4, o2 for
> n2 and o3 for n3). But if so, they does not appears on ObjectSpace
> listing, and what is the behaviour on gc?
>
> n1(1) -------------+---> "hidden" fixnum object (object id 3)
> n4(1) -------------+
> n2(2) -----------------> another "hidden" fixnum object (object id 5)
> n3(3) -----------------> another "hidden" fixnum object (object id 7)
>
> 2 - Or a single "internal" Fixnum object which is created ONCE and
> where is the VMT, who is asked for it's method everytime it's needed.
> So on this case n1, n2, n3 and n4 just stores the -(2**30) till
> (2**30)-1 number and asks the "internal" Fixnum object for methods to
> use with the value.
> n1(1) -------------+----> "internal" fixnum (check vmt)
> n2(1) -------------+
> n3(1) -------------+
> n4(1) -------------+
>
> Or any (or some kind of mix of) the two options above?
No, it's a third option: Fixnums are not really objects like others. With
Fixnum the object reference is the object itself. But you don't see that
directly because they are made to mostly work like other objects. You can
only observe it indirectly (like you did) in some places, namely
- absence from ObjectSpace
- prohibition of singleton methods
and maybe some more I don't recall because of my sleepyness. From a
pragmatic perspective this all doesn't really matter: since Fixnums are
immutable (no state changes, no singleton methods) anyway it doesn't matter
whether you have one instance representing a certain numeric value or
multiple. What in fact does matter in practice is that the implementation
of Fixnums in Ruby provides better performance than Fixnums that are
ordinary objects; in that case all numeric calculations would suffer because
they would incur the additional overhead of object creation and destruction.
HTH
Kind regards
robert