DEV Community

Discussion on: How to Determine if a String is a Palindrome (in JavaScript)

Collapse
 
trongtai37 profile image
trongtai37

Hi, i think your code look shorter and cleaner but the fact that author's code run faster with less complexity!.

Collapse
 
cyberhck profile image
Nishchal Gautam

Less complexity? About performance, you can scale out, you need to write code which is easy to maintain, read and modify, when you look at original method, you won't know what's going on without some serious effort, with second one, within 2-5 seconds you understand exactly what it's doing

Collapse
 
gustavosfq profile image
Gustavo Flores
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
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
amplanetwork profile image
Ampla Network • Edited

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
Enter fullscreen mode Exit fullscreen mode