var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
const length = arr.length
for(var i = 0; i < length; i++) {}
for(var i = 0; i < arr.length; i++) {}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reading length outside the for loop | |
reading length inside the for loop |
Test name | Executions per second |
---|---|
reading length outside the for loop | 34463.2 Ops/sec |
reading length inside the for loop | 362.4 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and other considerations.
Benchmark Definition
The benchmark definition is a JSON object that describes a simple JavaScript microbenchmark. It consists of:
Name
: A unique name for the benchmark.Description
: An optional description of the benchmark (in this case, null).Script Preparation Code
: The code that needs to be executed before running the benchmark. In this case, it creates an empty array (arr
) and initializes a variable i
to 0 using a while loop.Html Preparation Code
: Optional HTML code that can be used for preparation (in this case, null).Individual Test Cases
There are two test cases:
const length = arr.length; for(var i = 0; i < length; i++) {}
. This test case measures how fast a browser can execute a loop that accesses an array's length using the arr.length
property, but only after declaring the variable length
.for(var i = 0; i < arr.length; i++) {}
. This test case measures how fast a browser can execute a loop that accesses an array's length directly within the loop itself.Comparison
The comparison being tested is between accessing an array's length using two different approaches:
const length = arr.length
for(var i = 0; i < arr.length; i++) {}
This comparison aims to identify which approach is faster in a real-world scenario.
Pros and Cons
const length = arr.length;
) which may introduce additional memory allocation or lookup time.Other Considerations
arr.length
property is typically optimized to return a cached value. This means that accessing the length property may not incur significant additional overhead.Library
There is no specific library being used in this benchmark, but it relies on standard JavaScript features and syntax.
Special JS Feature/ Syntax
None mentioned.
Alternative Approaches
Other approaches to accessing an array's length could be:
Array.prototype.length
(which would add an additional property access)get length() { return arr.length; }
)However, these alternatives are not being tested in this benchmark.