I was wondering, with v8, when storing class attributes, is it more performant to use one variable with mixed types or one variable per type? Consider the following snippets (written in TypeScript for making the difference more clear):
type Type = "number" | "string";
type FooChild = number | string;
class Foo {
val?: FooChild;
_type: Type = "number";
constructor(initialValue: FooChild, initialType: Type) {
this.val = initialValue;
this._type = initialType;
}
getValue() {
return this.val;
}
}
class Bar {
str?: string;
val?: number;
_type: Type = "number";
constructor(initialValue: FooChild, initialType: Type) {
if (initialType === "string") this.str = initialValue as string;
else this.val = initialValue as number;
this._type = initialType;
}
getValue() {
return this._type === "string" ? this.str : this.val;
}
}
Afaik both should have advantages or defaults. Using one variable would have the problem that the JS engine might make assumptions on the types, optimize it for that type, and have to deoptimize it is it turns out that it actually also accepts numbers. But using multiple ones make that a lot of junk variables are lying around in each instance taking much space in memory for nothing.
I made this little benchmark to see if one outperforms the other, and it seems that using only one variable is more performant. But I also know that such benchmarks are usually not good at replicating real world situations, so I am seeking confirmation from more knowledgeable programmers.