This is a creation in Article, where the information may have evolved or changed.
Description
Before doing the Go project, encountered a question about the efficiency of the array deletion:
Looping arrays--judging--Deleting an array--getting the desired array
Example:
If I need to filter out arr2 in arr1,
The first way to write is as follows
arr1:=[]int{1,2,3......,999,1000}arr2:=[]int{5,10,15......,995,1000}for k, v := range arr1{ for _, vv := range arr2{ if v == vv { arr1= append(arr1[:k], arr1[k+1:]...) } }}
This will result in an error, because after deleting a number, the number of labels is not correct, so you need to delete in reverse:
for i := len(arr1) - 1; i >= 0; i-- { v := arr1[i] for _, vv := range arr2 { if v == vv { arr1 = append(arr1[:i], arr1[i+1:]...) } } }
Another way is not to delete, with a new Temparr to append:
var temp []int for _, v := range arr1 { for _, vv := range arr2 { if v == vv { temp = append(temp, v) } } }
Contrast
Test Source Github-demo
Tested by Golang's benchmark,
The results are as follows:
First, the method of deletion
The second, the temp Add method
Results
This test case runs 20,000 times in 1s, with approximately 86660ns, 97710ns per call
You can see that the way the array is used for deletion increases efficiency, of course, and I don't think there's much difference. Just for testing.