DEV Community

Discussion on: Solving Palindrome Check with JavaScript

Collapse
 
bloodbaz profile image
Chris Walsh

I would say that there is a more efficient method... you don't need to reverse the string after breaking it into a char array - make a read-only span from the string using .AsSpan() and then loop from 0 to str.Length/2 (rounded down is fine) and compare chars at both ends. No further heap allocations required and I'm guessing 10 times faster. As always however, this is a balancing act between efficiency and readability. On the other hand, palandrome tests are primarily of academic interest rather than something you come across in the real world. 👍

Collapse
 
xmohammedawad profile image
Mohammed Awad

never heard of this method before AsSpan(). thanks I will read about it, currently I'm learning how to write more efficient code so thanks

Collapse
 
tracygjg profile image
Tracy Gilmore

Happy to be proven wrong through a link into MDN but as far as I can tell AsSpan is not a String method in JS.