var obj = window.ololo;
var isNullOrUndefined = !obj
var isNullOrUndefined = obj === null || obj === undefined;
var isNullOrUndefined = typeof obj === 'undefined' || obj === null;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
not obj | |
obj is null or obj is undefined | |
type of obj is undefined or obj is null |
Test name | Executions per second |
---|---|
not obj | 9072898.0 Ops/sec |
obj is null or obj is undefined | 2963607.2 Ops/sec |
type of obj is undefined or obj is null | 8623800.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark measures how fast three different approaches can determine if an object obj
is null or undefined in JavaScript. The benchmark uses a simple script preparation code that assigns obj
to the global scope (window.ololo
) and then defines three different functions to test for nullity.
Approach 1: Using the Not Equal Operator (!)
var isNullOrUndefined = !obj;
Pros:
Cons:
obj
is falsy (i.e., null or undefined). If you're used to thinking of null
as falsey in a certain context, this might lead to unexpected behavior.!
operator has higher precedence than the equality operators, so it's essential to use parentheses around the expression for clarity.Approach 2: Using a Conditional Expression
var isNullOrUndefined = obj === null || obj === undefined;
Pros:
obj
is either null or undefined.Cons:
Approach 3: Using a Type Check
var isNullOrUndefined = typeof obj === 'undefined' || obj === null;
Pros:
obj
.Cons:
typeof
operator. The undefined
keyword has a specific meaning in JavaScript that might not be immediately apparent.typeof
and the wordy condition.Library: Window
The benchmark uses the global window
object as a variable for obj
. This is a common convention in JavaScript development. The window
object provides access to various attributes and methods related to the browser environment, including the DOM and APIs.
Special JS Feature: No Specific Features Mentioned
There are no special JavaScript features or syntaxes explicitly mentioned in this benchmark. However, it's worth noting that JavaScript has many advanced features, such as async/await, promise chaining, and functional programming concepts, which might be relevant to more complex benchmarks.
Alternatives
If you're looking for alternatives to MeasureThat.net, consider the following options:
benchmark
and jsperf
.Keep in mind that each of these alternatives has its own strengths, weaknesses, and use cases. MeasureThat.net is specifically designed for JavaScript microbenchmarks, so it's an excellent choice for comparing the performance of small snippets of code.