var n = 20;
var a = [];
var obj = {};
for (var i=0; i<a.length; i++) {
a[i] = i;
obj["obj" + i] = i;
}
r = Math.floor(Math.random()*n);
for (var i=0; i<a.length; i++) {
if (a[i] == r) break;
}
r = Math.floor(Math.random()*n);
var i = obj["obj"+r];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array | |
Object |
Test name | Executions per second |
---|---|
Array | 1183173.2 Ops/sec |
Object | 680346.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance difference between using arrays and objects in JavaScript for a simple search operation. The test creates an array and an object, populates them with numbers, and then searches for a randomly generated number within these data structures.
Script Preparation Code
The script preparation code initializes two variables: n
(an integer), a
(an empty array), and obj
(an empty object). It then uses a for
loop to populate the array and object with numbers, starting from 0 up to n-1
. The goal is to create a large dataset that will be used for benchmarking.
HTML Preparation Code
There is no HTML preparation code provided in this example. This might mean that the test focuses solely on JavaScript performance, without considering DOM manipulation or rendering.
Individual Test Cases
There are two individual test cases:
a
) and searches for a randomly generated number using for
loop.r = Math.floor(Math.random()*n);
for (var i=0; i<a.length; i++) {
if (a[i] == r) break;
}
This approach is straightforward and easy to understand.
obj
) with dynamic keys ("obj" + i
), which is similar to the array, but with an object-oriented twist.r = Math.floor(Math.random()*n);
var i = obj["obj"+r];
This approach leverages JavaScript's ability to create objects dynamically.
Pros and Cons
Here are some pros and cons of each approach:
for
loop.Library Usage
In this benchmark, no external libraries are used. The script and object creation rely solely on built-in JavaScript features.
Special JS Feature/ Syntax
The test case uses a special feature of JavaScript: dynamic property lookup. In the Object
test case, the key "obj" + i
is dynamically generated using string concatenation. This allows for flexible and dynamic storage of data in objects.
Alternatives
Other alternatives to consider when benchmarking array vs object performance include:
By considering these alternatives and using MeasureThat.net's benchmarking tool, developers can gain valuable insights into the performance characteristics of different data structures and algorithms in JavaScript.