From: Robert Klemme Date: 2009-12-22T02:26:33+09:00 Subject: Re: Ruby's implementation of Fixnum-assignment 2009/12/21 RichardOnRails : > I've made the following observations about Ruby's apparent > implementation: > > 1. Integer's in the range -2**30 to 2**30-1 are Fixnum's. Integers > outside that range are Bignum's > 2. For Fixnum "i",  i's object_id is twice i's value plus 1.  Said > another way, i's object_id is i''s binary value left-shifted with 1 as > padding. > 3. Object_id's of Bignum's close to the boundaries of Fixnum's bear no > apparent relationship to the Fixnum object_id's. All correct. > These observations suggest to me that an assignment statement like > "a=1" requires the interpreter to do no more than: > 1.  Search for the identifier "a" in the current scope. > 2.  If found, use it; if not, enter it in the current scope and then > use it. > 3. "Use it" means take the binary representation of the assigned > value,  left shift it with "1" padding, and make that current > object_id of the identifier "a". > 4. There is no need to locate free space in an memory pool where > object values for Bignums, Strings and other object are stored.  For > Fixnums, the object_id IS the value, just a little shifted. > > Is my speculation about this aspect of Ruby's implementation correct, > or am I all wet? Hm... While you have many things right, I don't fully agree. No variable (be it a local variable like "a" in your example or an instance variable like "@a") has an object id. Object id is a property of an object which might be referenced by many variables. Your step 3 actually mixes two separate things: evaluation of the expression of the right side of "=" and assignment. "Using" in an assignments means to take whatever the expression spits out and store it in the variable. Now, what your right hand expression yields is an object reference. For optimization purposes some object references are special in that they actually *are* the object (these are the "immediate values" which Gary mentioned, Fixnums for example). This does not make special treatment for assignments necessary. Rather, it makes special treatment for _method calls_ necessary. Because then the interpreter does not have to look up the object on the heap etc. Someone with more intimate knowledge of the implementation might be able to explain this better. But I believe it's important to point out that the difference is not in the assignment but in the right hand side expression which - in the case of a Fixnum - yields a special object reference. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/