Skip to content

Instantly share code, notes, and snippets.

@jsphkhan
Last active July 14, 2018 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsphkhan/d1fb85e889f2cc673789810dc95dc698 to your computer and use it in GitHub Desktop.
Save jsphkhan/d1fb85e889f2cc673789810dc95dc698 to your computer and use it in GitHub Desktop.
JavaScript Performance Benchmarking
//Perf benchmarking for array sorting.
//Run these lines in the browser console
//1. Bubble Sort
var t1 = performance.now();
var arr = [29, 30, 100, 300, 400, 12, 1, 45, 67, 29, 30, 100, 300, 400, 12, 1, 45, 67, 29, 30, 100, 300, 400, 12, 1, 45, 67];
for(var i=0;i<arr.length;i++) {
for(var j=0; j<arr.length-i-1;j++) {
if(arr[j] > arr[j+1]) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//console.log(arr);
var t2 = performance.now();
console.log('time taken: ' + (t2 - t1));
--------------------------------------------
//2. Native JS sort()
var t1 = performance.now();
var arr = [29, 30, 100, 300, 400, 12, 1, 45, 67, 29, 30, 100, 300, 400, 12, 1, 45, 67, 29, 30, 100, 300, 400, 12, 1, 45, 67];
arr = arr.sort(function(a,b) {
return a - b;
});
//console.log(arr);
var t2 = performance.now();
console.log('time taken: ' + (t2 - t1));
---------------------------------------------
//3. Merge Sort
function mergeSort (arr) {
if (arr.length === 1) {
// return once we hit an array with a single item
return arr
}
const middle = Math.floor(arr.length / 2)
const left = arr.slice(0, middle)
const right = arr.slice(middle)
return merge(
mergeSort(left),
mergeSort(right)
)
}
function merge (left, right) {
let result = []
let indexLeft = 0
let indexRight = 0
while (indexLeft < left.length && indexRight < right.length) {
if (left[indexLeft] < right[indexRight]) {
result.push(left[indexLeft])
indexLeft++
} else {
result.push(right[indexRight])
indexRight++
}
}
return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight))
}
var t1 = performance.now();
var arr = [29, 30, 100, 300, 400, 12, 1, 45, 67, 29, 30, 100, 300, 400, 12, 1, 45, 67, 29, 30, 100, 300, 400, 12, 1, 45, 67];
arr = mergeSort(arr);
var t2 = performance.now();
console.log('time taken: ' + (t2 - t1));
//Output: Merge Sort is fastest > Native sort() > Bubble Sort
############################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment