var map = new Map([["0",1]]);
var array = [1];
var symbol = Symbol('next');
var object = {["0"]: 1, [symbol]: 1 };
var weakMap = new WeakMap([[object,1]])
var x = 0;
x += map.get("0");
x += weakMap.get(object)
x += array[0]
x += object.a
x += object[symbol]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map.get | |
WeakMap.get | |
array[0] | |
object.a | |
object[symbol] |
Test name | Executions per second |
---|---|
Map.get | 17832704.0 Ops/sec |
WeakMap.get | 17493770.0 Ops/sec |
array[0] | 18560010.0 Ops/sec |
object.a | 18386114.0 Ops/sec |
object[symbol] | 17309896.0 Ops/sec |
The provided benchmark measures the performance difference between accessing elements of an array, object, map, and weak map.
Let's break down each test case:
array[0]
:[]
). In JavaScript, when you access an array element using square brackets, the browser needs to perform a lookup in the array's index table.object.a
:a
on the object using dot notation (.
). In JavaScript, when you access an object property using dot notation, the browser needs to perform a lookup in the object's property table.Map.get()
:"0"
using the Map.get()
method.WeakMap.get()
:object
using the WeakMap.get()
method.object[symbol]
:next
using square brackets ([]
). In JavaScript, when you access an object property using square brackets, the browser needs to perform a lookup in the object's index table.Comparison:
Method | Pros | Cons |
---|---|---|
Array[0] | Simple | Can be slower due to lookup in index table |
Object.a | Simple | Can be slower due to lookup in property table |
Map.get() | Optimized for lookups | Requires a Map object, which may not always be available |
WeakMap.get() | Optimized for lookups | Requires a WeakMap object, which may not always be available |
Object[symbol] | Simple | Can be slower due to lookup in index table |
In general, the fastest approach will depend on the specific use case and requirements. However, in general, using maps or weak maps for lookups can be faster than using arrays or objects.
Other alternatives:
Object.keys()
or Object.values()
instead of dot notation or square brackets to access object properties.Array.prototype.indexOf()
or Array.prototype.findIndex()
instead of direct indexing on an array element.Note that this benchmark is just one way to measure performance, and different test cases may prioritize different aspects (e.g., memory usage, CPU cycles).