Check for Palindromes Solution Performance

Check for Palindromes Solution Performance
0.0 0

#1

Hi all!

I just completed the “Check for Palindromes” challenge, and I noticed some interesting while experimenting with the other solutions found in the challenge guide.

The basic code solution is said to perform poorly when larger strings are passed to the function, and that the advanced code solution is the most performant of the three solutions given. However, when comparing the two different solutions in the console in Chrome, it seems the basic code solution actually performs better.

I ran both solutions on a palindrome that is 2709504 characters long. There are no special characters in this string, it’s simply the words “helloworld” repeated over and over again with no spaces in between.

I used the following code to measure the time each solution took to run:

var t0 = performance.now();
palindrome(longString);
var t1 = performance.now();
console.log("Solution took " + (t1 - t0) + " milliseconds.")

And for me, the basic solution completes in about half of the time that the advanced solution does. For the 2709504 character long string I mentioned about, the basic solution takes on average about 251.500ms and the advanced solution takes 640.800.

Does anyone know why this would be the case? Has anything changed since the challenge guide was written?

Joe


#2

Try the same test in Firefox, IE, Node etc? If the test you’ve done is correct, then I assume some optimisation within Chrome’s JS engine converts the basic code to something highly optimised under-the-hood. Note this is a problem with performance advice about hand-optimising JS, because it’s not like C (or C++, Java, etc). Not saying this is the case here, but whether one algorithm [written in JS and running in a browser] is more performant than another is highly dependent on JS engine/engine version. All the Ecmascript spec describes is what any given algorithm has to do for each step, it doesn’t tell the implementer (in this case Google or Chromium) how to do it.


Check for Palindromes - What's the difference
#3

Hi @DanCouper ,

Thanks for your response! Ah that makes sense, I haven’t had time to do the test in anything else yet. But when I get around to it, I’ll post the results here :slight_smile:

Thanks again!

Joe


#4

I’d recommend using a more complicated test string - something with capitals, punctuation, symbols, etc.

Your test string doesn’t have any capitals for toLowerCase() to have to do anything or any weird characters that would activate the RegEx search and replace (or skip).

In the advanced solution description, the author said his input string was the Bible. I think your test string might be the same order of magnitude, but it’s not the same complexity.