Skip to content

Instantly share code, notes, and snippets.

@omachala
Created October 15, 2021 21:59
Show Gist options
  • Select an option

  • Save omachala/09a8288d2ee8b27681cbc1d3bb3e8dd8 to your computer and use it in GitHub Desktop.

Select an option

Save omachala/09a8288d2ee8b27681cbc1d3bb3e8dd8 to your computer and use it in GitHub Desktop.
Javascript sort() vs Binary Search Tree (https://jsbench.github.io/#09a8288d2ee8b27681cbc1d3bb3e8dd8) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Javascript sort() vs Binary Search Tree</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
suite.add("const source = []", function () {
const source = []
new Array(100000).fill(null).forEach(_ => source.push(Math.random()))
const result = source.sort()
});
suite.add("class Node {", function () {
class Node {
value = null;
left = null;
right = null;
constructor(value) {
this.value = value;
}
add(value) {
if (value < this.value) {
if (this.left) {
this.left.add(value);
} else {
this.left = new Node(value);
}
}
if (value > this.value) {
if(this.right){
this.right.add(value)
} else {
this.right = new Node(value);
}
}
return this
}
values(){
const output = [];
if(this.left) output.push(...this.left.values())
output.push(this.value)
if(this.right) output.push(...this.right.values())
return output
}
}
class Tree {
root = null;
constructor(value){
this.root = new Node(value)
}
add(value) {
return this.root.add(value)
}
}
const tree = new Tree(0)
const source = new Array(100000).fill(null).forEach(_ => tree.add(Math.random()))
const result = tree.root.values()
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("Javascript sort() vs Binary Search Tree");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment