var Arr = new Array(100).fill(null).map(i => Math.random() * 100);
for (var i = 1; i < Arr.length; i++)
for (var j = 0; j < i; j++)
if (Arr[i] < Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
Arr.sort()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For loop | |
Array Sort |
Test name | Executions per second |
---|---|
For loop | 94931.0 Ops/sec |
Array Sort | 501265.4 Ops/sec |
In this benchmark, we are comparing two different sorting methods in JavaScript: a nested for
loop and the built-in Array.sort()
method. Here's a detailed look at what is being tested and the pros and cons of each approach:
For Loop Sort:
for (var i = 1; i < Arr.length; i++)
for (var j = 0; j < i; j++)
if (Arr[i] < Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
Array.sort():
Arr.sort();
The benchmark results show the number of executions per second for each sorting method:
Pros:
Cons:
Pros:
Cons:
Browser and Environment Dependency: The execution speed can vary significantly depending on the JavaScript engine, hardware, and operating system. The benchmark results from the iOS Mobile Safari indicate the performance can be improved on other platforms with different JavaScript engines (e.g., V8 in Chrome).
Alternatives:
In summary, this benchmark clearly highlights the substantial difference in performance between using a manual for
loop to sort an array and the built-in Array.sort()
. While the manual approach is more educational and can be modified for different sorting behavior, the built-in method is generally the best choice for most practical applications due to its efficiency and simplicity. Software engineers should prefer built-in methods for production code unless a specific custom sorting logic necessitates a manual implementation.