简体   繁体   中英

Why is one of the following algorithms faster than the other if you do more processing?

function reverseString(str) {
  let newStr = ''
  for (let i = (str.length - 1); i >= 0; i--) {
    newStr += str[i]
  }

  return newStr
}

// This algorithm is faster
function reverseString2(str) {
  str = str.split('')
  let left = 0
  let right = str.length - 1
  while (left < right) {
    const tmp = str[left]
    str[left] = str[right]
    str[right] = tmp
    left++
    right--
  }
  return str.join('')
}

Why is reverseString2 faster than reverseString if the function does more processing, converting the string to an array and then concatenating the whole array? The advantage is that the main algorithm is O(n/2) but the rest is O(n). Why does that happen?

The results are the following:
str size: 20000000
reverseString: 4022.294ms
reverseString2: 1329.758ms

Thanks in advance.

In the first function reverseString() , what is happening is that the loop is running 'n' times. Here 'n' is meant to signify the length of the string. You can see that you are executing the loop n times to get the reversed string. So the total time taken by this function depends on the value of 'n'.

In the second function reverseString2() , the while loop is running only n/2 times. You can understand this when you look at the left and the right variable. For one execution of the loop, the left variable is increasing by 1 and the right variable is decreasing by 1. So you are doing 2 updation at once. So for a n-length string, it only executes for n/2 times.

Although there are much more statements in the second function, but they are being executed much less time than those statements in the first function. Hence the function reverseString2() is faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM