var types = {
array: [1, 2, 3],
number: 123,
string: '123',
map: new Map([
[1, 1],
[2, 2],
[3, 3]
]),
set: new Set([1, 2, 3]),
buffer: new ArrayBuffer([1, 2, 3]),
boolean: true,
arrow: () => {},
function: function() {},
object: {}
}
var keys = Object.keys(types)
keys.map(key => typeof types[key] === "object")
keys.map(key => Object.prototype.toString.call(types[key]) === '[object Object]')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
typeof -> object | |
Object.prototype.toString.call -> object |
Test name | Executions per second |
---|---|
typeof -> object | 1969445.9 Ops/sec |
Object.prototype.toString.call -> object | 679313.1 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark tests two approaches to check if an object is an instance of Object
. The script preparation code defines an object types
with various types, including arrays, numbers, strings, maps, sets, buffers, booleans, and functions. It then extracts the keys of this object using Object.keys()
.
Options Compared
The benchmark compares two options:
typeof
: This operator returns a string indicating the type of the object. To check if an object is an instance of Object
, you can use typeof types[key] === "object"
.Object.prototype.toString.call
: This method returns a string representation of the object, prefixed with "[object Object]" for objects.Pros and Cons
typeof
:null
or undefined
would return "object"
), and may not work as expected in some cases (e.g., if the object is a primitive value).Object.prototype.toString.call
:typeof
, as it returns a specific string representation for objects, regardless of type coercion.typeof
.Library and Purpose
In this benchmark, the Map
and Set
constructors are used to create instances of these data structures. The ArrayBuffer
constructor is used to create a buffer object.
Special JS Feature or Syntax
This benchmark does not use any special JavaScript features or syntax beyond what's standard in modern JavaScript.
Other Alternatives
If you want to check if an object is an instance of Object
, there are other alternatives:
instanceof
: This operator checks if an object is an instance of a given constructor. You can use it like this: types[key] instanceof Object
.Object.create(null)
: This method creates a new object with no prototype chain, and you can check if it's an instance of Object
by verifying that its constructor is Object
.Keep in mind that these alternatives might have different performance characteristics or behavior depending on the specific use case.
In summary, the benchmark tests two common approaches to checking if an object is an instance of Object
: using typeof
and Object.prototype.toString.call
. The choice between these options depends on your priorities: speed vs. accuracy and robustness.