Skip to content

Instantly share code, notes, and snippets.

@milahu
Last active Jan 5, 2021
Embed
What would you like to do?
count number of lines in string (http://jsbench.github.io/#4cc806b4507ae063efc81900cdfb9b02) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>count number of lines in string</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 () {
// https://stackoverflow.com/questions/8488729
// how-to-count-the-number-of-lines-of-a-string-in-javascript
const s = document.body.innerHTML;
};
suite.add("match regex", function () {
// match regex
(s.match(/\n/g) || '').length
});
suite.add("split string", function () {
// split string
s.split('\n').length
});
suite.add("split regex", function () {
// split regex
s.split(/\n/).length
});
suite.add("for loop", function () {
// for loop
var c = 0;
for (var i = 0; i < s.length; i++)
if(s[i] == '\n') c++;
});
suite.add("for loop 2", function () {
// for loop 2
var c = 0;
for (const t of s) if(t == '\n') c++;
});
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("count number of lines in string");
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