Why was the object_id for true and nil changed in ruby2.0?

前端 未结 1 1307
悲&欢浪女
悲&欢浪女 2020-12-29 08:22

I came across this ruby object_id allocation question sometime back and then read this awesome article which talks about VALUE and explains why object_id of true, nil and fa

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 08:39

    A look at the Ruby source where these values are defined suggests that this has something to do with “flonums” (also see the commit where this was introduced). A search for ”flonum” came up with a message on the Ruby mailing list discussing it.

    This is a technique for speeding up floating point calculations on 64 bit machines by using immediate values for some floating point vales, similar to using Fixnums for integers. The pattern for Flonums is ...xxxx xx10 (i.e. the last two bits are 10, where for fixnums the last bit is 1). The object_ids of other immediate values have been changed to accomodate this change.

    You can see this change by looking at the object_ids of floats in Ruby 1.9.3 and 2.0.0.

    In 1.9.3 different floats with the same value are different objects:

    1.9.3p385 :001 > s = 10.234
     => 10.234 
    1.9.3p385 :002 > t = 10.234
     => 10.234 
    1.9.3p385 :003 > s.object_id
     => 2160496240 
    1.9.3p385 :004 > t.object_id
     => 2160508080 
    

    In 2.0.0 they are the same:

    2.0.0p0 :001 > s = 10.234
     => 10.234 
    2.0.0p0 :002 > t = 10.234
     => 10.234 
    2.0.0p0 :003 > s.object_id
     => 82118635605473626 
    2.0.0p0 :004 > t.object_id
     => 82118635605473626 
    

    0 讨论(0)
提交回复
热议问题