目前我正在实施一些排序算法.由于它属于算法的本质,因此使用该len()
方法对一些数组/切片的长度进行了大量调用.
现在,给出以下代码(部分)Mergesort算法:
for len(left) > 0 || len(right) > 0 {
if len(left) > 0 && len(right) > 0 {
if left[0] <= right[0] {
result = append(result, left[0])
left = left[1:len(left)]
} else {
result = append(result, right[0])
right = right[1:len(right)]
}
} else if len(left) > 0 {
result = append(result, left[0])
left = left[1:len(left)]
} else if len(right) > 0 {
result = append(result, right[0])
right = right[1:len(right)]
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:这些多个len()调用是否会对算法的性能产生负面影响?它是更好地作出对长度的临时变量right
和left
分得一杯羹?或者编译器本身会这样做吗?