<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>
var EMPTY_ARRAY = Object.freeze([]);
var values = {
"name": "",
"deviceGroup": {disabled: false, displayName: "MXChip IoT DevKit -…}"},
"definitionId": "urn:no3cohdk_:modelDefinition:c8feiwglut",
"properties": [],
"command": {item: undefined, value: undefined}
}
var obj = { a: 1, b: []}
immer.produce(values, draft => {
draft.x = 'asdf';
draft.y = 'blah';
draft.obj = obj;
draft.test = EMPTY_ARRAY;
})
immer.produce(values, draft => {
draft.x = 'asdf';
draft.y = 'blah';
draft.obj = obj;
draft.test = [];
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
EMPTY_ARRAY | |
New Array |
Test name | Executions per second |
---|---|
EMPTY_ARRAY | 165672.4 Ops/sec |
New Array | 164702.0 Ops/sec |
I'll explain the benchmark in detail.
What is being tested?
The benchmark tests two approaches to creating an array in JavaScript:
EMPTY_ARRAY
: Using an existing frozen array (Object.freeze([])
).New Array
: Creating a new empty array using the Array
constructor ([]
).Options compared:
The benchmark compares these two approaches, measuring their performance difference.
Pros and Cons of each approach:
EMPTY_ARRAY
might not be faster due to overhead of copying its contents.Library:
The benchmark uses immer
, a library that provides functional programming utilities for JavaScript. In this case, immer.produce
is used to create a draft of an object with specific properties.
Immer's purpose:
Special JS feature/syntax:
There is no special JavaScript feature or syntax used in this benchmark beyond the use of immer
and Object.freeze
.
Other alternatives:
If you're interested in exploring alternative approaches for creating empty arrays, here are a few options:
Array.from()
method:Array.from([]);
new Array(0)
method:new Array(0);
Both of these methods create an empty array, but they might have slightly different performance characteristics compared to the benchmark's approaches.
Keep in mind that performance differences may be negligible unless you're dealing with extremely large arrays or high-performance applications.