简体   繁体   English

如果您进行更多处理,为什么以下算法之一比另一种更快?

[英]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?如果reverseString进行更多处理,将字符串转换为数组然后连接整个数组,为什么 reverseString2 比reverseString2快? The advantage is that the main algorithm is O(n/2) but the rest is O(n).优点是主要算法是 O(n/2),但 rest 是 O(n)。 Why does that happen?为什么会这样?

The results are the following:结果如下:
str size: 20000000字符串大小: 20000000
reverseString: 4022.294ms反向字符串: 4022.294ms
reverseString2: 1329.758ms反向字符串2: 1329.758ms

Thanks in advance.提前致谢。

In the first function reverseString() , what is happening is that the loop is running 'n' times.在第一个 function reverseString()中,发生的事情是循环运行了“n”次。 Here 'n' is meant to signify the length of the string.这里的“n”表示字符串的长度。 You can see that you are executing the loop n times to get the reversed string.您可以看到您正在执行循环 n 次以获取反转的字符串。 So the total time taken by this function depends on the value of 'n'.所以这个 function 花费的总时间取决于“n”的值。

In the second function reverseString2() , the while loop is running only n/2 times.在第二个 function reverseString2()中,while 循环仅运行 n/2 次。 You can understand this when you look at the left and the right variable.当您查看leftright变量时,您可以理解这一点。 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.对于循环的一次执行, left变量增加 1, right变量减少 1。因此您一次进行 2 次更新。 So for a n-length string, it only executes for n/2 times.所以对于一个 n 长度的字符串,它只执行 n/2 次。

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.虽然第二个 function 中的语句要多得多,但它们的执行时间比第一个 function 中的语句要少得多。 Hence the function reverseString2() is faster.因此 function reverseString2()更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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