var list = [];
for (var i = 0; i < 1000 * 1000; i++) {
list.push(i);
}
list = list.slice(1);
list.splice(0, 1);
list.shift();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
splice | |
shift |
Test name | Executions per second |
---|---|
slice | 164.0 Ops/sec |
splice | 29070012.0 Ops/sec |
shift | 173746016.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
The provided JSON represents a benchmark test case on MeasureThat.net, which compares the performance of three different approaches to remove elements from an array: splice
, shift
, and slice
. The test aims to determine who is the fastest to modify the size of an array without pushing or shifting strings onto it.
Benchmark Definition
The original JSON defines a single benchmark case:
"Name": "slice VS splice VS shift: who is the fastest to keep constant size (fork no string push)"
This name gives us an idea of what's being tested: three different array manipulation methods and their performance when modifying the array's length without adding or removing strings.
Benchmark Preparation Code
The preparation code for this benchmark:
var list = [];
for (var i = 0; i < 1000 * 1000; i++) {
list.push(i);
}
This code creates an array list
with 1,000,000 elements and initializes it with integers from 0 to 999,999. This is done to ensure that the benchmark tests are run on a large enough dataset.
Options Compared
The three options being compared in this test case are:
slice()
method returns a shallow copy of a portion of an array. In this test, it's used to remove the first element from the array (list.slice(1)
).splice()
method removes elements from an array and returns the removed elements. It's used to remove the first element from the array (list.splice(0, 1)
).shift()
method removes the first element from an array and returns it. It's used to remove the first element from the array (list.shift()
).Pros and Cons of Each Approach
slice()
but can be slower than shift()
.slice()
since it doesn't create a new copy.shift()
due to modifying the original array.splice()
and slice()
for removing elements at the beginning of an array.splice()
if the removed element is not at the beginning.Library Usage
In this benchmark, no external libraries are used. The code relies solely on built-in JavaScript methods.
Special JS Features or Syntax
None of the tested features require special syntax or advanced JavaScript features beyond basic array manipulation techniques.
Other Alternatives
For similar use cases:
slice()
and shift()
.slice()
method on an array using the call()
method.splice()
or shift()
methods for more complex array manipulations.For testing and benchmarking, MeasureThat.net provides a unique platform that allows users to compare performance of different JavaScript code snippets. By comparing the execution times of various methods, developers can make informed decisions about which approach to use in their own projects.