Golang: fill set or iteration slices
2 min readAug 20, 2020
When comparing two arrays or looking for matches in them etc.
For which number of elements is it more profitable to use a map filled with all the elements of the array(time complexity O (n) ) or double iterations of arrays (time complexity O (n²))?
Implement a set in Go is to use a map with value empty structs. An empty struct doesn’t use any memory.
m := make(map[string]struct{}) //createm["one"] = struct{}{} //writeif val, exist := m[v1]; exist { //read}
Read from slice is faster than map.
Use iteration slices
for _, v1 := range slice1 { for _, v2 := range slice2 { if v1 == v2 { cnt++ break } }}
Use map
for _, v := range slice2 { //fill m[v] = struct{}{}}for _, v := range slice1 { //check if _, exist := m[v]; exist { cnt++ }}
For a small number of elements, double iterations of arrays are faster, but for 200 elements, the times are the same.