var sym = [Symbol("key1"), Symbol("key2"), Symbol("key3"), Symbol("key4"), Symbol("key5"), Symbol("key6"), Symbol("key7"), Symbol("key8"), Symbol("key9"), Symbol("key0")];
var str = ["key1", "key2", "key3", "key4", "key5", "key6", "key7", "key8", "key9", "key0"];
var foo1 = {
[sym[0]]: 0,
[sym[1]]: 0,
[sym[2]]: 0,
[sym[3]]: 0,
[sym[4]]: 0,
[sym[5]]: 0,
[sym[6]]: 0,
[sym[7]]: 0,
[sym[8]]: 0,
[sym[9]]: 0,
};
var foo2 = {
[str[0]]: 0,
[str[1]]: 0,
[str[2]]: 0,
[str[3]]: 0,
[str[4]]: 0,
[str[5]]: 0,
[str[6]]: 0,
[str[7]]: 0,
[str[8]]: 0,
[str[9]]: 0
};
for(const k of sym) foo1[k] = 1;
for(const k of str) foo2[k] = 1;
let sum = 0
for (const k of sym) sum += foo1[k];
let sum = 0
for (const k of str) sum += foo2[k];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Symbol | |
String | |
Symbol sum | |
String sum |
Test name | Executions per second |
---|---|
Symbol | 2816764.0 Ops/sec |
String | 2823161.2 Ops/sec |
Symbol sum | 2925757.2 Ops/sec |
String sum | 2959609.8 Ops/sec |
I'll provide an in-depth explanation of the provided benchmark.
Benchmark Overview
The benchmark measures the performance difference between using Symbol properties and string indices (also known as arrays) for object access in JavaScript. The benchmark consists of four test cases:
Symbol
: Accessing elements using Symbol properties.String
: Accessing elements using string indices (arrays).Symbol sum
: Calculating the sum of element values by iterating over Symbol-located elements.String sum
: Calculating the sum of element values by iterating over array-located elements.Library and Special JS Features
There is no explicit library mentioned in the benchmark, but JavaScript's built-in Symbol
feature is used to create unique property names. The Symbol
feature was introduced in ECMAScript 2015 (ES6) as a way to create new property names that cannot be accessed by string indices.
Options Compared
The benchmark compares two options:
Pros and Cons
Symbol Properties:
Pros:
Cons:
Symbol()
String Indices (Arrays):
Pros:
Cons:
Benchmark Results
The latest benchmark results show the following execution rates per second:
String sum
: 2959609.75 executions per second (Chromium 119)Symbol sum
: 2925757.25 executions per second (Chromium 119)String
: 2823161.25 executions per second (Chromium 119)Symbol
: 2816764.0 executions per second (Chromium 119)These results suggest that accessing elements using Symbol properties is slightly faster than using string indices.
Other Alternatives
While the benchmark focuses on Symbol properties and string indices, other alternatives for object access include:
obj[Symbol('name')]
) for dynamic or runtime-determined property names.Keep in mind that the performance benefits of each approach depend on specific use cases, code organization, and the trade-offs between developer intuition, maintainability, and performance optimization.