JSFiddle - React, Tailwind, and code Playground
by tbinetruy
HTML
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
JavaScript
function createRandomArray() {
var arr = [];
for (var i=0, t=40000; i<t; i++) {
arr.push(Math.round(Math.random() * 200))
}
return arr
}
// mode 1 is the only one that runs in same time for sorted and unsorted array
// i believe it's because it's the only case where the block if(arr[i] < 100) get ignored by interpreter (compare with mode 3 which does the same this, except that if(arr[i] < 100) has to run)
function delay(arr, mode) {
var a = 1
// dummy loop
for(j = 0; j < 1000; j++) {
// loop going through array
for(i = 0; i < 40000 - 1; i++) {
// condition to get same level of nesting
if(mode < 3) {
if(mode === 1) {
if(arr[i] < 100)
a = a
}
if(mode === 2) {
if(arr[i] < 100)
a = a+1
}
}
if(mode > 2) {
if(arr[i] < 100) {
if(mode === 3)
a = a
if(mode === 4)
a = a+1
}
}
}
}
}
function run(arr, mode) {
var t0 = performance.now();
delay(arr, mode)
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
}
var compareNumbers = (a, b) => a - b
run(createRandomArray(), 1)
run(createRandomArray().sort((a,b) => compareNumbers(a,b)), 1)
run(createRandomArray(), 2)
run(createRandomArray().sort((a,b) => compareNumbers(a,b)), 2)
run(createRandomArray(), 3)
run(createRandomArray().sort((a,b) => compareNumbers(a,b)), 3)
run(createRandomArray(), 4)
run(createRandomArray().sort((a,b) => compareNumbers(a,b)), 4)