var array = [Array(40)].map(_=>Math.ceil(Math.random()*40))
array.splice(0, 20)
while (array.length > 20) array.shift();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.splice() | |
array.shift() |
Test name | Executions per second |
---|---|
array.splice() | 53471800.0 Ops/sec |
array.shift() | 108417344.0 Ops/sec |
The benchmark presented compares two different approaches for removing elements from the beginning of an array in JavaScript: using Array.prototype.splice()
and using Array.prototype.shift()
. The benchmark evaluates their performance by measuring how many times each operation can be executed per second on a given device.
array.splice(0, 20)
:
while (array.length > 20) array.shift();
:
array.splice()
:
splice()
has to handle the internal re-indexing of the array elements after removal, which can create performance bottlenecks, especially with larger arrays or repeated use.array.shift()
:
splice()
, shift()
also involves re-indexing of the array after each removal, which can accumulate additional time costs.Performance Context: The performance will greatly depend on the size of the array and how many elements are being removed. For small arrays, the performance difference may be negligible, but for larger arrays, the method selected could impact performance significantly.
Browser Differences: The benchmark results show significant performance differences between the two methods, with array.shift()
executing over 42 million times per second, demonstrating it is notably faster than array.splice()
at about 16 million executions per second. This could vary based on the JavaScript engine optimizations in the browser being used, so results may not be consistent across different environments.
slice()
or array destructuring can be employed.This benchmark clearly outlines the performance implications of two common methods for array modification in JavaScript. Understanding the pros and cons of each operation allows developers to make informed decisions based on the specific requirements and constraints of their projects.