dope2/benchmarks/rbtree_bench.js

88 lines
2.5 KiB
JavaScript

import createTree from "functional-red-black-tree";
function benchmark(N) {
// fastest
function map() {
let t = new Map();
const startTime = Date.now();
for (let i=0; i<N; ++i) {
t.set(Math.random(), Math.random());
}
const endTime = Date.now();
return endTime - startTime;
}
const durInPlace = map();
console.log("in-place:", durInPlace, "ms");
// slower by constant factor
function fun() {
let t = createTree();
const startTime = Date.now();
for (let i=0; i<N; ++i) {
t = t.insert(Math.random(), Math.random());
}
const endTime = Date.now();
return endTime - startTime;
}
const durFunc = fun();
console.log("functional:", durFunc, "ms");
// a bit slower still
function funNoGC() {
const old = new Array(N);
let t = createTree();
const startTime = Date.now();
for (let i=0; i<N; ++i) {
old[i] = t; // prevent garbage collection
t = t.insert(Math.random(), Math.random());
}
const endTime = Date.now();
return endTime - startTime;
}
const durFuncNoGC = (N <= 1000000) ? funNoGC() : "";
console.log("functional (no GC):", durFuncNoGC, "ms");
// slowest (won't scale)
function copying() {
let t = new Map();
const startTime = Date.now();
for (let i=0; i<N; ++i) {
t = new Map(t);
t.set(Math.random(), Math.random());
}
const endTime = Date.now();
return endTime - startTime;
}
const durCopying = (N <= 50000) ? copying() : "";
console.log("copying:", durCopying, "ms");
// slower than slowest
function copyingNoGC() {
const old = new Array(N);
let t = new Map();
const startTime = Date.now();
for (let i=0; i<N; ++i) {
old[i] = t; // prevent garbage collection
t = new Map(t);
t.set(Math.random(), Math.random());
}
const endTime = Date.now();
return endTime - startTime;
}
const durCopyingNoGC = (N <= 10000) ? copyingNoGC() : "";
console.log("copying (no GC):", durCopyingNoGC, "ms");
return [N, durInPlace, durFunc, durFuncNoGC, durCopying, durCopyingNoGC];
}
const results = [];
for (const N of [100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000]) {
console.log("N =", N);
results.push(benchmark(N));
}
console.log("N;in-place;functional;functional-NoGC;copying;copying-NoGC");
for (const [N, durInPlace, durFunc, durFuncNoGC, durCopying, durCopyingNoGC] of results) {
console.log(`${N};${durInPlace};${durFunc};${durFuncNoGC};${durCopying};${durCopyingNoGC}`);
}