Skip to content

Instantly share code, notes, and snippets.

@angryziber
Created June 14, 2019 14:12
Show Gist options
  • Save angryziber/34e5f4840d23b4355f82955da733b9c2 to your computer and use it in GitHub Desktop.
Save angryziber/34e5f4840d23b4355f82955da733b9c2 to your computer and use it in GitHub Desktop.
Test JavaScript object access performance (in TypeScript)
interface Named {
firstName: string;
lastName: string;
}
class Person implements Named {
firstName: string;
lastName: string;
constructor(firstName: string = '', lastName: string = '') {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
function fullName(named: Named) {
return named.firstName + ' ' + named.lastName;
}
it('', () => {
const staticData: Named = {firstName: 'Anton', lastName: 'K'};
const copiedData: Named = {...staticData};
const extendedData = {firstName: 'Anton', lastName: 'K'} as any;
extendedData.xxx = 'something else';
const modifiedData: Named = {firstName: 'Anton', lastName: 'K'};
modifiedData.firstName = 'John';
const json = JSON.parse(JSON.stringify(staticData));
const person = new Person('Anton', 'K');
const person1: Person = Object.assign(new Person(), staticData);
const person2: Person = Object.setPrototypeOf(staticData, new Person());
const person3: Person = Object.setPrototypeOf(staticData, Person.prototype);
measureTime(() => fullName(staticData));
measureTime(() => fullName(copiedData));
measureTime(() => fullName(extendedData));
measureTime(() => fullName(modifiedData));
measureTime(() => fullName(json));
measureTime(() => fullName(person));
measureTime(() => person.fullName);
measureTime(() => person1.fullName);
measureTime(() => person2.fullName);
measureTime(() => person3.fullName);
});
function measureTime(f: () => void) {
const start = Date.now();
for (let i = 0; i < 100000000; i++) {
f();
}
console.log(f.toString(), f(), Date.now() - start);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment