function isPalindrome(string) { let left = 0; let right = string.length - 1; while (left <= right) { if (string[left] !== string[right]) return false; left++; right--; } return true; } const isPalindrome2 = str => str.split('').reverse().join('') === str; console.time('isPalindrome'); for(var i = 0; i < 100000000; i++) { isPalindrome('asdfgfdsa') } console.timeEnd('isPalindrome') console.time('isPalindrome2'); for(var i = 0; i < 100000000; i++) { isPalindrome2('asdfgfdsa') } console.timeEnd('isPalindrome2') isPalindrome: 4212.408935546875 ms isPalindrome2: 60999.298095703125 ms
Not so sure either we can do shorter and faster :-)
function isPalindrome(string) { let left = 0; let right = string.length - 1; while (left <= right) { if (string[left] !== string[right]) return false; left++; right--; } return true; } const isPalindrome2 =(str) => { const l = str.length; for(let i=0; i< (l / 2) >> 0; i++) { if (str[i] !== str[l-i-1]) return false; } return true; } console.time('isPalindrome'); for(var i = 0; i < 100000000; i++) { isPalindrome('asdfgfdsa') } console.timeEnd('isPalindrome') console.time('isPalindrome2'); for(var i = 0; i < 100000000; i++) { isPalindrome2('asdfgfdsa') } console.timeEnd('isPalindrome2') ; VM254:26 isPalindrome: 3210.27978515625 ms VM254:31 isPalindrome2: 2888.925048828125 ms
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Not so sure either we can do shorter and faster :-)