ruby when to eigenclasses come into existence

Do Eigenclasses exist prior to a singleton method being defined on a Object or Class. ie Do they always exist or come in existence when a singleton method or class method in defined?


Every object always has a singleton class. Period. No ifs, no buts, no exceptions.

Depending on how clever the compiler or interpreter is, it may or may not perform some performance optimizations. But like all performance optimizations, those are not allowed to change the result of the program, so even if those performance optimizations do lead to certain states where a particular singleton class does not actually exist, the program still must behave as if it did exist, so you wouldn't be able to tell anyway. After all, that's pretty much the definition of "performance optimization".

Some Ruby implementations may do some optimizations, others may do other optimizations, some may even not do any optimizations at all. You can't tell from the result of your program, and you shouldn't care, you mustn't care.

For example, YARV performs the following optimizations:

  • Since almost no object has singleton methods, creating a singleton class for every object would be a waste of memory, therefore singleton classes are created lazily: when you create a singleton method ( def foo.bar or Object#define_singleton_method ), when you open up the singleton class ( class << foo ), and when you ask for an object's singleton class ( Object#singleton_class ).

  • Since almost every class has some sort of class method, the overhead of lazily creating a singleton class doesn't make sense, so for classes, the singleton class is always created eagerly.

  • But this is a private internal implementation detail of YARV. JRuby may do it differently. IronRuby may do it differently. MacRuby may do it differently. MRuby may do it differently. Topaz may do it differently. Rubinius may do it differently. MagLev may do it differently. Even the next patchlevel of YARV may do it differently.

    If you look at the singleton class it's there. If you don't look at it, it doesn't matter whether it's there. So, semantically, it's always there.


    for objects like class, when a new class is created its eigenclass is also created, and of their object when they are created.

    example:- creating a class

    class User; end
    

    or

    User = Class.new
    

    its eigenclass is also created at the same time,

    and there a separate eigenclass is created for every object of User class

    链接地址: http://www.djcxy.com/p/95438.html

    上一篇: 为什么fixnum没有特征类?

    下一篇: 红宝石何时才能生成本征类