Skip to content

Instantly share code, notes, and snippets.

@koron
Last active November 15, 2016 16:21
Show Gist options
  • Save koron/582455f91c49b5bd2994e8b128c604b2 to your computer and use it in GitHub Desktop.
Save koron/582455f91c49b5bd2994e8b128c604b2 to your computer and use it in GitHub Desktop.
'use strict';
const ITERATION = 100000000;
const DATA = [
'http://',
'ftp://',
'htts://',
'',
];
const FUNCS = [
ishttp0,
ishttp1,
ishttp4,
];
FUNCS.forEach(function(f) {
bench(f, ITERATION);
});
function bench(f, n) {
var st = Date.now();
var cnt = 0;
for (var i = 0; i < n; ++i) {
if (f(DATA[i % DATA.length])) {
++cnt;
}
}
console.log(Date.now() - st, cnt);
}
function ishttp0(s) {
return s[0] === 'h' && s[1] === 't' && s[2] === 't' && s[3] === 'p';
}
function ishttp1(s) {
return s[0] === 'h' && s.substring(0, 4) === 'http';
}
function ishttp2(s) {
return s.substring(0, 4) === 'http';
}
function ishttp3(s) {
return s.startsWith('http');
}
function ishttp4(s) {
return startsWith(s, 'http');
}
function startsWith(s, t) {
if (s.length < t.length) {
return false;
}
for (var i = 0; i < t.length; ++i) {
if (s[i] !== t[i]) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment