binarez
binarez

Reputation: 809

Do I gain anything from packing numbers into an array for a Javascript (Typescript) struct?

I'm declaring a Typescript class "Sample" but the same idea applies to Javascript.

export enum SampleData
{
    PositionX = 0,
    PositionY,
    TangentX,
    TangentY,

    Max
};

export class Sample
{
    data: number[] = new Array( SampleData.Max );
    x() { return this.data[SampleData.PositionX]; }
    y() { return this.data[SampleData.PositionY]; }
}

Do I gain anything from packing numbers into an array for a Javascript (Typescript) struct? By "gain" I mean perf, memory, helping gc, etc.

vs

export class Sample
{
    x : number;
    y : number;
    tanX : number;
    tanY : number;
}

Sample instances will ultimately end up in an array of Samples.

Upvotes: 0

Views: 368

Answers (1)

Tibos
Tibos

Reputation: 27833

No.

Instance property lookups are optimized by the JavaScript engine to avoid a map lookup and be similar to a C structure, where each property is at a known offset inside the structure.

Adding an array in the mix attempts to do the same thing at the language level, but it simply creates another layer of indirection, making things slightly slower.

Keep it simple. Let the JS engine worry about optimizations until you are ready to benchmark and notice the problem areas in your code.

Upvotes: 3

Related Questions