3 ms·
The code as written is polymorphic, but the JIT will make an optimized version if it detects that a function is only called with one or two types at runtime. A
by tveita 6y ago
The code as written is polymorphic, but the JIT will make an optimized version if it detects that a function is only called with one or two types at runtime.
As I understand it "megamorphic" just means the point where the JIT gives up on specializing for each type. So you'd have e.g.
Monomorphic - JIT emits code specialized for one type.
Bimorphic - JIT emits two specialized versions of the code, with a branch in front that checks the type.
Megamorphic - JIT emits polymorphic code that will work with any type. Prevents inlining and many optimizations.
This comes up when optimizing Java code, since the JVM only specializes call sites that are monomorphic or bimorphic.
If you're implementing a set class you might want to have specialized subclasses for, say, empty sets or one-element sets, so you can implement certain methods more efficiently - e.g. the intersection of an empty set is always an empty set. So you add the classes MySet, MyEmptySet and MyOneElementSet. But now your code runs slower than it did with just MySet, because your method call sites are Trimorphic and can't be inlined anymore.
This seems like a good explanation as well: https://mrale.ph/blog/2015/01/11/whats-up-with-monomorphism.html https://mrale.ph/blog/2015/01/11/whats-up-with-monomorphism.... and says that V8 will optimize for up to 4 different types before going megamorphic.
In the example in TFA, m() will be called with 5 different classes (createMixin(Base), createMixin(createMixin(Base))...) so V8 will generate megamorphic code instead of specializing.
- saagarjha 6y agoRight, I know that, it's just that I've usually heard this called "monomorphic"/"bimorphic"/"trimorphic" (rarely) and then just "polymorphic" for when the JIT stops specializing. I just have never heard of "megamorphic".
- chrisseaton 6y ago'Bimorphic', 'trimorphic', 'megamorphic' are all increasing degrees of 'polymorphism'. Something that is 'bimorphic' is also 'polymorphic', but is not 'megamorphic'.