const obj = Object.create(null);
const result = [];
for (i = 0; i < 100_000; i++) {
result.push(obj[i]);
}
const obj = {};
const result = [];
for (i = 0; i < 100_000; i++) {
result.push(obj[i]);
}
const obj = Object.create(null);
const result = [];
for (i = 0; i < 100_000; i++) {
result.push(i in obj);
}
const obj = {};
const result = [];
for (i = 0; i < 100_000; i++) {
result.push(i in obj);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.create(null); | |
{} | |
key in Object.create(null) | |
key in {} |
Test name | Executions per second |
---|---|
Object.create(null); | 406.7 Ops/sec |
{} | 353.6 Ops/sec |
key in Object.create(null) | 405.1 Ops/sec |
key in {} | 336.2 Ops/sec |
What is tested: The provided benchmark compares the performance of three approaches:
Object.create(null)
: This creates an object without any prototype chain, effectively making it a "null" object. It's used to test the performance of accessing properties on such an object.{}
(empty object literal): This creates a normal JavaScript object with no inherent properties.key in Object.create(null)
and key in {}
: These expressions are used to test if a property exists on each of these objects.Options compared:
Object.create(null)
, attempting to access an unknown property throws a TypeError
. In contrast, when using {}
, the same property lookup will simply return undefined
.key in Object.create(null)
, it will always throw a TypeError
if the key is unknown, whereas with {}
, the result will be false
.Pros and cons:
Object.create(null)
has a clear security benefit, as it makes it more difficult for malicious code to access potentially sensitive properties.{}
is generally faster and more convenient but may expose potential vulnerabilities if not used carefully.Library/dependency:
None of these benchmarks explicitly use any external libraries or dependencies. The only library being used here is Object
, which is a built-in JavaScript object.
Special JS feature/syntax: None of the test cases rely on special JavaScript features like async/await, Promises, or web workers.
Other alternatives:
Object.assign()
or Object.fromEntries()
.In summary, this benchmark provides a useful comparison between three common approaches to handling unknown properties in JavaScript. While it's primarily focused on performance, understanding the trade-offs and implications of each approach can help developers make more informed decisions about their code.