var acts = "BRA|BRA|FLR|VSL|BRA".split("|");
for (var i = 0; i < acts.length -1; i++) {
if (acts[i] == "BRA") acts.splice(i, 1);
}
var acts = "BRA|BRA|FLR|VSL|BRA".split("|");
var i = acts.length;
while (i--) {
if (acts[i] == "BRA") acts.splice(i, 1);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For loop | |
While loop |
Test name | Executions per second |
---|---|
For loop | 7489558.0 Ops/sec |
While loop | 4818987.0 Ops/sec |
I'll explain the benchmark in detail.
Benchmark Overview
The benchmark compares the performance of two loops: For Loop and While Loop, specifically when removing elements from an array using splice()
method. The goal is to determine which loop approach is faster on Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0.
Options Compared
The benchmark compares two approaches:
for (var i = 0; i < acts.length -1; i++) {
if (acts[i] == "BRA") acts.splice(i, 1);
}
var i = acts.length;
while (i--) {
if (acts[i] == "BRA") acts.splice(i, 1);
}
Pros and Cons
Library and Special JS Features
The benchmark uses no specific libraries or special JavaScript features. However, it's worth noting that splice()
method modifies the original array, which can lead to unexpected behavior in certain scenarios.
Other Alternatives
If you want to explore alternative loop approaches, consider:
for...of
) instead of traditional loops.forEach()
method for a more modern and efficient way to iterate over arrays.In conclusion, this benchmark provides a simple yet informative comparison between two common loop approaches in JavaScript: For Loop and While Loop. By understanding the trade-offs and pros and cons of each approach, developers can make informed decisions when writing their own code.