var items = new Array(100000);
var aNum = 1000;
for (var index = 0, item = null; (item = items[index]); index++) { var test = aNum - item; }
for (var index = 0; index < items.length; index++) {
var item = items[index];
var test = aNum - item;
}
items.forEach(item => { var test = aNum - item; });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for normal | |
foreach |
Test name | Executions per second |
---|---|
for | 9985860.0 Ops/sec |
for normal | 35.1 Ops/sec |
foreach | 4218.8 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared options, pros and cons of each approach, and other considerations.
Benchmark Definition
The looping with various 2
benchmark defines three test cases:
for
: This loop uses a traditional for
loop with an index variable (index
) that increments on each iteration.for normal
: Similar to the first one, but without the null initialization of item
.foreach
: This test case uses the forEach
method on the items
array.Script Preparation Code
The script preparation code initializes two variables:
items
: a new array with 100,000 elements.aNum
: an integer variable set to 1,000.This code is executed before each benchmark run.
Html Preparation Code
There is no HTML preparation code provided for this benchmark.
Test Cases and Options Compared
The three test cases are compared in terms of their performance:
for
vs for normal
: The main difference between these two loops is the initialization of the item
variable. In the first loop, item
is initialized to null
, while in the second loop, it's not initialized at all.foreach
vs traditional loops: The forEach
method on an array is generally faster than using a traditional for
loop because it avoids the overhead of indexing and incrementing.Pros and Cons of Each Approach
for
)index
.for normal
(no null initialization)foreach
MethodOther Considerations
for
loop's null initialization of item
can lead to performance issues if the array contains non-nullable values. In contrast, the foreach
method avoids this problem altogether.Alternatives
If you're looking for alternative approaches, consider:
Set
objects can provide efficient iteration over unique values.Keep in mind that these alternatives may not be suitable for all use cases, and their performance impact will depend on your specific requirements and JavaScript version support.