Why is this loop back so much slower than going forward?

I have an answer to another guy's question here How to count the occurrence of a string in a string? Therefore, I played with the algorithms here , and after benchmarking some functions, I was wondering why the reverse cycle was much slower than forward.

graph

Performance test here


NOTE. This code below does not work, as expected, there are others that work (this is not a question of this question), keep in mind before copying> Paste 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; } 
+4
source share
4 answers

I myself found a bottle neck.

when i did it

 for (i = string.length; i > 1; i--) { 

I accidentally deleted "var" from var i , so I made i global. After the correction, I got the expected results.

 for (var i = string.length; i > 1; i--) { 

I never thought it could be a HUGE difference, so pay attention to the guys.

Benckmark test fixed here

Before

Before

After:

After

PS: for practical use, DO NOT use these functions, the indexOf version is much faster.

+2
source

I think there is an error in the reverse test:

for (i = string.length; i > 1; i--) {

it should be

for (i = string.length - 1; i >= 0; i--) {

If i is string.length , string.charAt(i) is undefined. Do this several thousand times, and this can lead to a significant difference.

Here's a modified test , which seems to be much closer to identical scores.

+4
source

What data are you testing. If your data has many matching prefixes, but not many false matches, on the contrary, it can affect it.

I’m also used to the fact that a search error in such cases as “aaabbaaa” will try to find “aab”, it will match aa, and then it will fail, and then it will continue to work from the third a and will not work.?

0
source

Since they are not completely mirror functions, add console.log() inside all the if and else both functions and compare the results, you will see that the tests are not fair.

You did something wrong. I suggest that they both work as expected, even after the start of testing.

0
source

Source: https://habr.com/ru/post/1416476/


All Articles