Golang array filtering operation benchmark efficiency comparison

Source: Internet
Author: User
Tags benchmark
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.