I have a answer to another guy question here How to count string occurrence in string?
So I was playing with algorithms here, and after benchmarking some functions I was wondering why a backwards loop was significantly slower than forward.

NOTE: This code below does not work as supposed to be, there are
others that work (thats not the point of this question), be aware
before Copying>Pasting it
Forward
function occurrences(string, substring) {
var n = 0;
var c = 0;
var l = substring.length;
for (var i = 0, len = string.length; i < 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;
for (i = string.length; i > 1; i--) {
if (string.charAt(i) == substring.charAt(c)) {
c--;
} else {
c = l;
}
if (c < 0) {
c = l;
n++;
}
}
return n;
}
I found the bottle-neck myself.
when I did this
I accidentaly deleted the "var" from
var i, so I’ve madeiglobal.After fixing it I got the expected results.
I never though that this may be a HUGE difference, so pay attention guys.
Fixed Benckmark test here
Before:
After:
PS: for practical use, do NOT use this functions, the indexOf version is much faster.