Skip to content

Instantly share code, notes, and snippets.

@belozer
Last active August 19, 2019 10:41
Show Gist options
  • Save belozer/35ec4a8199d42ffc7de83998f0de34f8 to your computer and use it in GitHub Desktop.
Save belozer/35ec4a8199d42ffc7de83998f0de34f8 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>#slice #for</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;
Benchmark.prototype.setup = function () {
var rnd = () => String(Math.random);
var slice = [].slice;
var results = [];
function resolve(callback) {
var retVal = callback(rnd(), rnd(), rnd(), rnd(), rnd());
// console.log(retVal);
// if (retVal.length !== 5) {
// throw 'FAIL:retVal';
// }
results.push(retVal);
}
};
suite.add("slice", function () {
/** slice **/
resolve(function classnames() {
let className = '';
const uniqueCache = new Set();
// Use arguments instead rest operator for better performance.
const classNameList = [].slice.call(arguments);
for (const value of classNameList) {
if (value === '' || value === undefined || uniqueCache.has(value)) {
continue;
}
uniqueCache.add(value);
if (className.length > 0) {
className += ' ';
}
className += value;
}
return className;
})
});
suite.add("2 for", function () {
/** 2 for **/
resolve(function classnames() {
let className = '';
const uniqueCache = new Set();
for (let i=0; i < arguments.length; i++) {
const value = arguments[i];
if (value === '' || value === undefined || uniqueCache.has(value)) {
continue;
}
uniqueCache.add(value);
if (className.length > 0) {
className += ' ';
}
className += value;
}
return className;
})
});
suite.add("slice", function () {
/** slice **/
resolve(function classnames(...strings) {
let className = '';
const uniqueCache = new Set();
for (const value of strings) {
if (value === '' || value === undefined || uniqueCache.has(value)) {
continue;
}
uniqueCache.add(value);
if (className.length > 0) {
className += ' ';
}
className += value;
}
return className;
})
});
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("#slice #for");
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