var objs = []
var i = 0
for (i; i < 100000; i++) {
var obj = {}
obj.x = Math.random() * 100
obj.y = Math.random() * 100
obj.z = Math.random() * 100
objs.push(obj)
}
objs.sort((a, b) => {
if (a.x != b.x) {
return a.x - b.x
}
if (a.y != b.y) {
return a.y - b.y
}
return a.z - b.z
})
objs.sort((a, b) => {
return (a.x - b.x) || (a.y - b.y) || (a.z - b.z)
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IF statement | |
OR assignment |
Test name | Executions per second |
---|---|
IF statement | 130.5 Ops/sec |
OR assignment | 146.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches for sorting an array of objects using JavaScript: IF statements and OR (||) assignment.
Script Preparation Code
The script preparation code generates an array of 100,000 objects with random properties x
, y
, and z
. This is done to provide a consistent input for the sorting function being tested.
Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark focuses solely on JavaScript performance.
Individual Test Cases
There are two test cases:
Pros and Cons
Library and Special JS Feature/ Syntax
There is no library used in this benchmark. However, the test case uses a JavaScript feature called arrow functions, which was introduced in ECMAScript 2015 (ES6). Arrow functions provide a concise way to define small functions without declaring them with function
or var
. In this benchmark, arrow functions are used to simplify the sorting function.
Alternative Approaches
Other approaches for sorting arrays of objects might include:
Array.prototype.sort()
and providing a custom comparison function.Keep in mind that the choice of approach depends on specific requirements, performance constraints, and personal coding style.