我试图了解 Golang 中切片追加与分配的性能,我认为通常分配会更好,但在这段代码中,看起来追加更好。我试图找出原因 - 但我正在努力解决这个问题。
这是 Leetcode 中的合并排序数组,下面的版本 1 给了我 3 毫秒的运行时间
func merge(nums1 []int, m int, nums2 []int, n int) {
tmpSlice := make([]int, m+n)
tmpIndex := 0
index1 := 0
index2 := 0
for index1 < m {
value1 := nums1[index1]
for index2 < n {
value2 := nums2[index2]
if value1 <= value2 {
break
} else {
tmpSlice[tmpIndex] = value2 \\ <-- Assign
index2++
tmpIndex++
}
}
tmpSlice[tmpIndex] = value1 \\ <-- Assign
index1++
tmpIndex++
}
copy(nums1, tmpSlice[:tmpIndex])
copy(nums1[tmpIndex:], nums2[index2:])
}
下面的版本 2 给了我 0 毫秒的运行时间
func merge(nums1 []int, m int, nums2 []int, n int) {
tmpSlice := make([]int, 0, m+n)
tmpIndex := 0
index1 := 0
index2 := 0
for index1 < m {
value1 := nums1[index1]
for index2 < n {
value2 := nums2[index2]
if value1 <= value2 {
break
} else {
tmpSlice = append(tmpSlice, value2) \\ <-- Append
index2++
tmpIndex++
}
}
tmpSlice = append (tmpSlice, value1) \\ <-- Append
index1++
tmpIndex++
}
copy(nums1, tmpSlice[:tmpIndex])
copy(nums1[tmpIndex:], nums2[index2:])
}
两个版本的唯一区别就是append vs assign,append速度更快。Append 正在检查内存分配,然后进行分配,对吗?Append 不应该更慢吗?
白衣非少年
相关分类