Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
class vs fn
(version: 1)
Comparing performance of:
create arrClass vs create 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 function 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; }; } let arrClass; let arrFn;
Tests:
create arrClass
arrClass = Array.from({length: 1000}, (_, i) => new StateClass());
create arrFn
arrFn = Array.from({length: 1000}, (_, i) => createStateClosure());
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
create arrClass
create 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
create arrClass
49105.2 Ops/sec
create arrFn
46757.3 Ops/sec
Autogenerated LLM Summary
(model
gpt-4o-mini
, generated 10 months ago):
The benchmark defined in the provided JSON is designed to compare the performance of two different approaches to lazy initialization in JavaScript: using a class (`StateClass`) versus a closure (`createStateClosure`). Let's break down the test and its components. ### Benchmarks Compared 1. **Implementation via Class (`StateClass`)**: - The `StateClass` is created with a constructor that initializes a private `_state` property to `null`. The `getState()` method checks if `_state` has been initialized: - If it hasn't, it simulates an expensive operation by generating an array of random numbers, computes its sum, and stores both in `_state`. - On subsequent calls, it returns the already initialized `_state`. 2. **Implementation via Closure (`createStateClosure`)**: - This method declares a variable `state` within the outer function scope and returns an inner function (`getState`) that behaves similarly to the class method. - The inner function checks if `state` is `null`, simulates the same expensive operation if true, and caches the result. ### Performance Analysis - **Execution Results**: - `create arrClass`: Approximately 49,105 executions per second. - `create arrFn`: Approximately 46,757 executions per second. ### Pros and Cons #### Class Implementation (`StateClass`) **Pros**: - **Encapsulation**: The use of a class offers a clearer structure, encapsulating the state and logic in an object-oriented style. - **Future Extensions**: Easier to extend with inheritance and other object-oriented principles. **Cons**: - **Overhead**: Classes might introduce overhead due to object instantiation and prototype chain lookups. #### Closure Implementation (`createStateClosure`) **Pros**: - **Simplicity**: A functional programming approach that avoids the overhead associated with classes. - **Lightweight**: Since closures do not involve creating objects, they may perform faster under some conditions. **Cons**: - **Readability**: For developers unfamiliar with functional patterns, closures can be less intuitive than class-based structures. ### Other Considerations - **Memory Usage**: Depending on the implementation and usage patterns, memory consumption may vary. Classes may maintain more metadata, whereas closures can sometimes be more efficient. - **Compatibility and Use Cases**: Certain contexts (like React components) might favor one approach over the other based on state management needs. ### Similar Alternatives 1. **Factory Functions**: Similar to closures, but can be designed to return different objects for each call. 2. **Module Pattern**: Another method of encapsulating state and behavior using closures that can provide private and public methods. 3. **React Hooks**: For lazy state initialization in functional components (`useState`), leveraging React's built-in hooks may be an alternative approach for UI-focused applications. ### Conclusion The benchmark effectively illustrates how two distinct paradigms in JavaScript can achieve similar goals—lazy initialization—with different performance implications. A direct comparison in terms of execution speed provides insights, but each approach has its own trade-offs that developers should consider based on application architecture, performance needs, and team familiarity with paradigms.
Related benchmarks:
fast_deep_equal - lodash.isEqual test567l898978666
приведения к числу и строке в или выражении 3
а я думал создание итератора будет дороже
双轴图刻度对齐算法性能对比
双轴图对齐算法性能对比
双轴图对齐算法性能对比(version2)
Intl.collator O(N*M) vs native String.prototype.includes O(N+M)ы
class vs fn: 2
class vs fn: 3
Comments
Confirm delete:
Do you really want to delete benchmark?