<!--your preparation HTML code goes here-->
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
class TransformComponent {
constructor(scaleX = 1.0, scaleY = 1.0, rotation = 0.0) {
this.scaleX = scaleX;
this.scaleY = scaleY;
this.rotation = rotation;
}
scale(factor = 1.0) {
this.scaleX *= factor;
this.scaleY *= factor;
}
};
for(let i = 0; i < 10000; i++) {
const transform = new TransformComponent(i, i, i);
transform.scale(2.0);
}
const components = new Map;
const noop = () => {};
const componentsMethodCaller = (factory, methodName, values) => {
const methods = components.get(factory);
return (methods[methodName] || noop).apply(null, values);
}
const transformFactory = (scaleX = 1.0, scaleY = 1.0, rotation = 0.0) => {
return {
scaleX,
scaleY,
rotation,
};
}
components.set(transformFactory, {
scale(component, factor = 1.0) {
component.scaleX *= factor;
component.scaleY *= factor;
},
});
for(let i = 0; i < 10000; i++) {
const transform = transformFactory(i, i, i);
componentsMethodCaller(transformFactory, 'scale', 2.0);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Class method | |
Factory manager |
Test name | Executions per second |
---|---|
Class method | 4393.5 Ops/sec |
Factory manager | 1118.0 Ops/sec |
The provided JSON defines a benchmark that compares two different approaches for creating and using transform components in JavaScript: a class-based implementation and a factory-based implementation with a method manager.
TransformComponent
class, which encapsulates the properties and methods for transformation. Each instance of the class has methods that can be invoked directly (e.g., scale
).Map
for dynamic dispatch. The componentsMethodCaller
function invokes methods on these objects.In this benchmark, the class method outperformed the factory manager approach primarily due to reduced overhead from dynamic method invocation. Each approach has distinct advantages and trade-offs that can guide a developer's choice depending on the specific use case and performance needs. These considerations are crucial when designing a system architecture, especially in the context of large applications where efficiency and maintainability are paramount.