Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
class vs fn: 2
(version: 1)
Comparing performance of:
arrClass vs arrFn
Created:
10 months ago
by:
Guest
Jump to the latest result
HTML Preparation code:
<!--your preparation HTML code goes here-->
Script Preparation code:
// Класс с ленивой инициализацией class StateClass { constructor() { this._state = null; } getState() { if (this._state === null) { // Имитация более дорогой операции const arr = Array.from({length: 1000}, (_, i) => i * Math.random()); this._state = { data: arr, computed: arr.reduce((a, b) => a + b, 0), timestamp: Date.now() }; } return this._state; } } // Замыкание с ленивой инициализацией function createStateClosure() { let state = null; return { getState: () => { if (state === null) { // Имитация более дорогой операции const arr = Array.from({length: 1000}, (_, i) => i * Math.random()); state = { data: arr, computed: arr.reduce((a, b) => a + b, 0), timestamp: Date.now() }; } return state; } }; } const arrClass = Array.from({length: 1000}, (_, i) => new StateClass()); const arrFn = Array.from({length: 1000}, (_, i) => createStateClosure());
Tests:
arrClass
arrClass.forEach(i => i.getState());
arrFn
arrFn.forEach(i => i.getState());
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
arrClass
arrFn
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
10 months ago
)
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36
Browser/OS:
Chrome 137 on Mac OS X 10.15.7
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
arrClass
613848.2 Ops/sec
arrFn
142007.0 Ops/sec
Autogenerated LLM Summary
(model
gpt-4o-mini
, generated 10 months ago):
The benchmark compares the performance of two different approaches to managing state in JavaScript: using a class with lazy initialization and using a function with a closure, also with lazy initialization. Specifically, it measures the execution speed of getting the state from instances of each approach. ### Options Compared 1. **StateClass (Class-based approach)** - This approach uses a class (`StateClass`) that encapsulates state management. It has a constructor that initializes `_state` to `null`, and the actual data state is generated only when it is first requested through the `getState` method. The `_state` is populated with an array of randomly generated numbers and some computed values. 2. **createStateClosure (Function-based approach)** - This approach defines a closure through a function (`createStateClosure`). Instead of using a class, it keeps the state variable within the scope of the function. The first time `getState` is called on the returned object, it initializes `state` similar to the `StateClass` approach. ### Pros and Cons **Class-based Approach (StateClass)** - **Pros:** - Object-oriented structure, allowing for easy inheritance and polymorphism. - Logical grouping of methods and properties. - Can be better for large applications that benefit from object-oriented design. - **Cons:** - May involve more overhead due to the class instantiation process. - Potentially more memory consumption if many instances are created compared to the closure approach. **Function-based Approach (createStateClosure)** - **Pros:** - Simplicity and a lightweight structure suitable for functional programming paradigms. - Reduces overhead as it doesn't require managing classes and instances explicitly. - Functions in JavaScript are first-class citizens, allowing for more flexibility when creating and manipulating closures. - **Cons:** - Less intuitive for developers accustomed to class-based design, which might affect code readability. - Less support for advanced object-oriented features like inheritance. ### Alternative Considerations Both approaches are valid, and the choice between them largely depends on the project's requirements. Alternatives include: - **Modules:** Using ES6 modules to encapsulate state and logic which can provide better organization than multiple classes or closures. - **Control Libraries:** Utilizing libraries like React, Vue, or Redux for managing state can simplify development and provide powerful tools for state management across applications. - **Function Prototypes:** Instead of using ES6 classes, you can create objects through prototypes, though it's less common in modern JavaScript development. ### Benchmark Results The benchmark results indicate that the class-based approach (`arrClass`) executed approximately **613,848** times per second, while the function-based approach (`arrFn`) executed approximately **142,007** times per second. This suggests that, for this specific case, the class-based approach is significantly faster than the closed function approach in the execution environment tested (Chrome 137 on Mac OS X). ### Conclusion When deciding between class-based and function-based lazy initialization in JavaScript, consider the size of your application, performance requirements, and the familiarity of your team with object-oriented or functional programming paradigms. The benchmark results favor the class-based method in this instance, although outcomes may vary in different contexts or with larger data sets.
Related benchmarks:
fast_deep_equal - lodash.isEqual test567l898978666
а я думал создание итератора будет дороже
双轴图刻度对齐算法性能对比
双轴图对齐算法性能对比
双轴图对齐算法性能对比(version2)
3Intl.collator O(N*M) vs native String.prototype.includes O(N+M)ы2334
3Intl.collator O(N*M) vs native String.prototype.includes O(N+M)ы234
class vs fn
class vs fn: 3
Comments
Confirm delete:
Do you really want to delete benchmark?