var list = [];
for (let i = 0; i < 1000; i++) {
list.push({'s':'usd', 'p':i});
}
list.push({'s':'cad', 'p':13})
list.push({'s':'cad', 'p':14})
list.push({'s':'cad', 'p':15})
list=list.slice(list.length-1000)
list.push({'s':'cad', 'p':13})
list.push({'s':'cad', 'p':14})
list.push({'s':'cad', 'p':15})
list.splice(0, list.length-1000);
list.push({'s':'cad', 'p':13})
list.push({'s':'cad', 'p':14})
list.push({'s':'cad', 'p':15})
while(list.length>1000){
list.shift();
}
list.push({'s':'cad', 'p':13})
list.push({'s':'cad', 'p':14})
list.push({'s':'cad', 'p':15})
for(let i=0; i<(list.length-998); i++){
list.shift();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
splice | |
shift -while | |
shift-for |
Test name | Executions per second |
---|---|
slice | 278724.3 Ops/sec |
splice | 162104.8 Ops/sec |
shift -while | 919740.4 Ops/sec |
shift-for | 928122.4 Ops/sec |
Let's break down the provided benchmark and its various components.
Benchmark Definition The benchmark is designed to measure the performance of three different methods for adding new elements to the end of an array in JavaScript:
list.push()
list.splice()
while
loop and shift()
method (Shift-While)These methods are commonly used in JavaScript development, but they have different overheads and efficiency characteristics.
Options Compared
The three options compared in this benchmark are:
slice()
method to create a new array with the last 1000 elements of the original array.splice()
method to remove the first 1000 elements from the original array, effectively creating an empty array.while
loop and the shift()
method to repeatedly remove elements from the end of the array until it reaches the desired size.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
slice()
or splice()
.Library Usage
None of the benchmark options explicitly use any libraries. However, the slice()
method is a built-in JavaScript function that creates a new array with a specified range of elements from an existing array.
Special JS Features or Syntax
The only special syntax used in this benchmark is the use of template literals (var list = [];\r\nfor (let i = 0; i < 1000; i++) {\r\n list.push({'s':'usd', 'p':i});\r\n}
) to create a large array with 1000 elements. This syntax is widely supported in modern browsers and Node.js environments.
Other Alternatives
For this specific benchmark, there are no other alternatives that would significantly change the outcome. However, if you're interested in exploring other methods for adding new elements to an array, some possible options include:
Array.prototype.push.apply()
or Array.prototype.unshift()
with a separate array or iterable as an argument.Keep in mind that the choice of method ultimately depends on the specific requirements and constraints of your project.