Skip to content

Instantly share code, notes, and snippets.

@Kjaer
Created January 30, 2020 11:39
Show Gist options
  • Save Kjaer/aec1445402fde01082163b685ed15c52 to your computer and use it in GitHub Desktop.
Save Kjaer/aec1445402fde01082163b685ed15c52 to your computer and use it in GitHub Desktop.
Performance tips for O(n²) on JavaScript iterations.
function charUnique(s) {
var r = {},
i, x;
for (i = s.length - 1; i > -1; i--) {
x = s[i];
if (r[x])
return false;
r[x] = true;
}
return true;
}
function charIndexOfUnique(s) {
var r = [],
i, x;
for (i = s.length - 1; i > -1; i--) {
x = s[i];
if (r.indexOf(x)>0)
return false;
r.push[x];
}
return true;
}
function charCodeUnique(s) {
var r = [],
i, x;
for (i = s.length - 1; i > -1; i--) {
x = s.charCodeAt(i);
if (r[x])
return false;
r[x] = true;
}
return true;
}
function timer(f) {
var i;
var t0;
var string = [];
for (i = 32; i < 127; i++)
string[string.length] = String.fromCharCode(i);
string = string.join('');
console.time("start")
for (i = 0; i < 10000; i++)
f(string);
console.timeEnd("start")
}
timer(charUnique);
// 86 ms
timer(charIndexOfUnique);
// 24 ms
timer(charCodeUnique)
// 12 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment