const arr = Array.from({ length: 5000 }).map(() => Math.random());
const serialized = JSON.stringify(arr);
const deserialized = JSON.parse(serialized);
deserialized.map(x => 0.0);
const serializedAgain = JSON.stringify(deserialized);
const arr = Array.from({ length: 5000 }).map(() => Math.random());
const buffer = new ArrayBuffer(arr.length * 4);
const view = new Float32Array(buffer, 0, 4);
view.map((_, idx) => arr[idx]);
view.map(() => 0.0);
const view2 = new Float32Array(buffer, 0, 4);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON serialization | |
ArrayBuffer serialization |
Test name | Executions per second |
---|---|
JSON serialization | 450.2 Ops/sec |
ArrayBuffer serialization | 2441.7 Ops/sec |
This benchmark compares the performance of two different approaches for serializing and deserializing large arrays in JavaScript: JSON serialization and ArrayBuffer serialization.
JSON Serialization
In this approach, an array is created using Array.from()
with 5000 random numbers. The array is then serialized to a JSON string using JSON.stringify()
. The resulting JSON string is parsed back into an array using JSON.parse()
, and the array is modified by mapping over it and setting all elements to 0. The modified array is then serialized again to another JSON string.
ArrayBuffer Serialization
In this approach, an array is created using Array.from()
with 5000 random numbers. An ArrayBuffer is created with a length equal to the product of the array's length and 4 (assuming 32-bit floating-point numbers). A Float32Array view is created from the ArrayBuffer, which maps over the original array and sets its elements to 0. The modified array is then mapped again to set all elements to 0.
Pros and Cons
JSON Serialization:
Pros:
Cons:
ArrayBuffer Serialization:
Pros:
Cons:
Library Usage
None of the test cases use any external libraries.
Special JS Feature/Syntax
Neither test case uses any special JavaScript features or syntax beyond standard JavaScript syntax. However, it's worth noting that the Array.from()
method and Float32Array
constructor are part of ECMAScript 2015 (ES6) standards.
Other Alternatives
Alternatives to ArrayBuffer serialization include:
Uint8Array
and Atob()
for binary serialization.In summary, this benchmark compares the performance of two approaches for serializing and deserializing large arrays in JavaScript. While JSON serialization is easy to implement and widely supported, ArrayBuffer serialization can be faster but requires more advanced knowledge and may not be supported by all browsers or Node.js versions.