javascript - Why this loop backwards is much slower than going forward? -
i have answer guy question here how count string occurrence in string? playing algorithms here, , after benchmarking functions wondering why backwards loop slower forward.
note: code below not work supposed be, there others work (thats not point of question), aware before copying>pasting it
forward
function occurrences(string, substring) { var n = 0; var c = 0; var l = substring.length; (var = 0, len = string.length; < len; i++) { if (string.charat(i) == substring.charat(c)) { c++; } else { c = 0; } if (c == l) { c = 0; n++; } } return n; }
backwards
function occurrences(string, substring) { var n = 0; var l = substring.length - 1; var c = l; (i = string.length; > 1; i--) { if (string.charat(i) == substring.charat(c)) { c--; } else { c = l; } if (c < 0) { c = l; n++; } } return n; }
i think backwards test has bug:
for (i = string.length; > 1; i--) {
should be
for (i = string.length - 1; >= 0; i--) {
when i
string.length
, string.charat(i)
undefined. several thousand times, , yield substantial difference.
here's modified test seems yield closer identical performances.
Comments
Post a Comment