<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function initArray(W = 1000, H = 1000, C = 100) {
let array = Array(H);
for (let y = 0; y < H; y++) {
array[y] = Array(W);
for (let x = 0; x < W; x++) {
array[y][x] = Array(C);
for (let z = 0; z < C; z++) {
array[y][x][z] = _.random(0, 255);
}
}
}
return array;
}
function createRandomPoint(w, h, c) {
return {
x: _.random(0, w - 1),
y: _.random(0, h - 1),
z: _.random(0, c - 1),
value: _.random(0, 255)
};
};
function updateWithSpread(prevImg) {
const { x, y, z, value } = createRandomPoint(W, H, C);
const newChannel = [
prevImg[y][x].slice(0, z),
value,
prevImg[y][x].slice(z + 1)
];
const newCol = [
prevImg[y].slice(0, x),
newChannel,
prevImg[y].slice(x + 1)
];
const newImg = [prevImg.slice(0, y), newCol, prevImg.slice(y + 1)];
return newImg;
};
var W = 500, H = 500, C = 50;
var bigArray = initArray(W, H, C);
var bigImmutable = Immutable.fromJS(bigArray);
bigArray = updateWithSpread(bigArray);
const {x,y,z,value} = createRandomPoint(W, H, C);
bigImmutable = bigImmutable.setIn([y,x,z], value);
const {x,y,z,value} = createRandomPoint(W, H, C);
bigArray[y][x][z] = value;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread operator | |
Immutable.js deep List | |
Mutating the array in place |
Test name | Executions per second |
---|---|
Spread operator | 163514.0 Ops/sec |
Immutable.js deep List | 449999.7 Ops/sec |
Mutating the array in place | 1256127.5 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark measures the performance of three different approaches for updating a large, nested array in JavaScript:
...
) to create a new copy of the affected parts of the array, and then assigns this new value to a specific position.Options Compared
The benchmark compares the performance of these three approaches:
Pros and Cons of Each Approach
Other Considerations
When choosing between these approaches, consider the following factors:
Alternative Approaches
Other approaches you might consider include:
Array.prototype.slice()
: Creating a new copy of the affected parts using slice()
.Array.prototype.forEach()
: Updating values using forEach()
and modifying individual elements.Keep in mind that each approach has its trade-offs, and the best choice depends on your specific use case and requirements.