let cachedGlobal;
function getGlobal() {
if (cachedGlobal) {
return cachedGlobal;
}
if (typeof globalThis !== 'undefined' && globalThis) {
cachedGlobal = globalThis;
}
return cachedGlobal
}
for (let i = 0; i < 4000; i++) {
const global = getGlobal();
}
function getGlobal() {
if (typeof globalThis !== 'undefined' && globalThis) {
return globalThis;
}
}
for (let i = 0; i < 4000; i++) {
const global = getGlobal();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Memoize typeof call | |
Call typeof every time |
Test name | Executions per second |
---|---|
Memoize typeof call | 451.8 Ops/sec |
Call typeof every time | 480.6 Ops/sec |
Let's break down the provided JSON and benchmark information.
Overview of the Benchmark
The test case is designed to measure the performance difference between two approaches when checking if globalThis
(a property of the global object) exists:
cachedGlobal
) so that it's not recalculated every time.globalThis
exists.Options Compared
The two options being compared are:
Pros and Cons of Each Approach
Memoized Approach (cachedGlobal)
Pros:
globalThis
every time.Cons:
cachedGlobal
) requires memory.Non-Memoized Approach (always check)
Pros:
Cons:
globalThis
can be slower than memoizing the result.Library/Functionality
In this benchmark, there is no explicit library or function being used beyond the standard JavaScript functions and variables (e.g., typeof
, globalThis
). However, some libraries like Lodash might provide similar functionality if you were using it in your code.
Special JS Features/Syntax
There are no special JS features or syntax being utilized in this benchmark. It's a basic example of comparing two approaches to check if globalThis
exists.
Other Alternatives
To test similar scenarios, alternative benchmarks could be created with different approaches, such as:
Keep in mind that the specific use case and requirements will influence the design of an alternative benchmark.