<!--your preparation HTML code goes here-->
const simpleObject = () => ({
property: Math.random()
})
class SimpleClass {
property = Math.random()
}
const methodObject = () => ({
getProperty() {
return Math.random()
}
})
class MethodClass {
getProperty() {
return Math.random()
}
}
const accessorObject = () => ({
get property() {
return Math.random()
}
})
class AccessorClass {
get property() {
return Math.random()
}
}
const result = simpleObject().property
const result = new SimpleClass().property
const result = methodObject().getProperty()
const result = new MethodClass().getProperty()
const result = accessorObject().property
const result = new AccessorClass().property
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Simple object | |
Simple class | |
Method object | |
Method class | |
Accessor object | |
Accessor class |
Test name | Executions per second |
---|---|
Simple object | 128585392.0 Ops/sec |
Simple class | 107972248.0 Ops/sec |
Method object | 101302056.0 Ops/sec |
Method class | 122080592.0 Ops/sec |
Accessor object | 10168510.0 Ops/sec |
Accessor class | 117083168.0 Ops/sec |
The benchmark titled "Accessor vs method vs direct property access" evaluates different approaches to accessing properties in JavaScript objects and classes. Specifically, it compares the performance of:
Simple Object: Direct property access in a plain object.
const result = simpleObject().property
Simple Class: Direct property access in a class field.
const result = new SimpleClass().property
Method Object: Accessing a property value through a method in an object.
const result = methodObject().getProperty()
Method Class: Accessing a property via a method defined in a class.
const result = new MethodClass().getProperty()
Accessor Object: Using getters to access a property in an object.
const result = accessorObject().property
Accessor Class: Using a getter in a class to access a property.
const result = new AccessorClass().property
From the benchmark's results, the performance (in executions per second) shows a clear preference for the simplest forms of property access:
Overall, engineers should weigh the need for speed against architectural considerations when choosing the method of property access in their JavaScript applications.