function isNull(anObj) {
return anObj == null;
}
var aStr = "asdfljbsflaskdnflkbsadf";
var test = aStr == null;
var test = isNull(aStr);
var test = aStr === null;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Pure Box | |
Function | |
Pure |
Test name | Executions per second |
---|---|
Pure Box | 10960222.0 Ops/sec |
Function | 5402901.5 Ops/sec |
Pure | 9005846.0 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Definition
The benchmark tests three different approaches to check if a variable is null or not:
var test = aStr == null;
var test = isNull(aStr);
(where isNull
is a custom function defined in the script preparation code)var test = aStr === null;
Library and Custom Function
The custom function isNull(anObj)
is used in the "Function" approach. This function simply checks if the input object anObj
is equal to null using the loose equality operator (==
). The purpose of this library is to provide a simple way to check for null values.
Comparison Options
Here's a summary of each option:
==
) to compare the value of aStr
with null. The ==
operator performs type coercion, which means it will return true even if aStr
is not exactly null (e.g., if it's an empty string). This approach may lead to false positives.isNull(anObj)
to check for null values. The isNull
function simply checks if the input object is equal to null using the loose equality operator (==
). While this approach provides a clear and explicit way to check for null values, it may not be as efficient as other methods.===
) to compare the value of aStr
with null. The ===
operator performs type coercion, but in this case, since aStr
is a string and null is an object, the comparison will always return false.Pros and Cons
Here's a summary of each approach:
Other Considerations
When writing benchmarks like this one, consider the following:
Alternatives
Other approaches to checking for null values in JavaScript include:
typeof
: var test = typeof aStr === 'object' && aStr === null;
instanceof
: var test = aStr instanceof Object && aStr === null;
&&
with null
: var test = aStr !== undefined && aStr !== null;
Each of these alternatives has its own trade-offs and use cases, but they can provide more accurate results than the loose equality operators used in the benchmark.