Based on:
So these two objects will have different shapes:
function ObjA(a, b) {
this.a = a;
this.b = b;
}
function ObjB(a, b) {
return {
a: a,
b: b
};
}
// shape: { b } -> { a } -> {}
var a = new ObjA(1, 2);
// shape: { a, b }
var b = ObjB(1, 2);
But will these objects have the same shape?
function ObjA(a, b) {
this.a = a;
this.b = b;
}
function ObjB(a, b) {
this.a = a;
this.b = b;
}
var a = new ObjA(1, 2);
var b = new ObjB(1, 2);
- So the fact that they're different classes doesn't mean anything to the js engine?
- If I were to add a function to ObjB's prototype, would that result in ObjA and ObjB instances having different shapes?
- From a performance perspective, are object literals "better" as long as you don't plan to use the prototype, or doesn't it matter?
Say I have the following function:
function biggerThanFive(obj) {
var some_val = obj.getValue();
if (some_val > 5) {
return true;
} else {
return false;
}
}
Imagine that during the lifetime of my application, I pass 100 objects with different shapes to biggerThanFive
.
This would result in biggerThanFive
being megamorphic.
- Am I correct in assuming that this function wouldn't be optimized at all?
- Would this function still be megamorphic even though all these objects has
getValue
stored on their prototype objects, and that the prototype objects are all the same shape? - Would it be possible to limit megamorphic code by dividing megamorphic pieces into their own function? Like this:
// monomorphic?
function biggerThanFive(obj) {
var some_val = getValue(obj);
if (some_val > 5) {
return true;
} else {
return false;
}
}
// megamorphic?
function getValue(obj) {
return obj.getValue();
}
Thank you for the links, and for taking the time! 😊