Is it good practice to use pointer to channel? For example I read the data concurrently and pass those data map[string]sting
using channel and process this channel inside getSameValues()
.
func getSameValues(results *chan map[string]string) []string {
var datas = make([]map[string]string, len(*results))
i := 0
for values := range *results {
datas[i] = values
i++
}
}
The reason I do this is because the chan map[string]string
there will be around millions of data inside the map and it will be more than one map.
So I think it would be a good approach if I can pass pointer to the function so that it will not copy the data to save some resource of memory.
I didn't find a good practice in effective go. So I'm kinda doubt about my approach here.
Channels, maps, and functions are the same size as a pointer. Therefore, the runtime cost of copying a value of these types is identical to copying a pointer to the value.
Go channels are used for communicating between concurrently running functions by sending and receiving a specific element type's data. When we have numerous Goroutines running at the same time, channels are the most convenient way for them to communicate with one another.
Are channels implicitly passed by reference in go ? Yes, the reference types in Go are slice , map and channel .
It is poor practice to use pointers to channels, maps, functions, interfaces, or slices for efficiency.
Values of these types have a small fixed size independent of the length or capacity of the value. An internal pointer references the variable size data.
Channels, maps, and functions are the same size as a pointer. Therefore, the runtime cost of copying a value of these types is identical to copying a pointer to the value.
Interfaces are two × the size of a pointer, and slices are three × the size of a pointer. The cost of copying a value of these types is higher than copying a pointer. That extra copying cost is often lower or equal to the cost of dereferencing the pointer.
In Go, there are six categories of value that are passed by reference rather than by value. These are pointers, slices, maps, channels, interfaces and functions.
Copying a reference value and copying a pointer should be considered equal in terms of what the CPU has to actually do (at least as a good approximation).
So it is almost never useful to use pointers to channels, just like it is rarely useful to use pointers to maps.
Because your channel carries maps, the channel is a reference type and so are the maps, so all the CPU is doing is copying pointers around the heap. In the case of the channel, it also does goroutine synchronisation too.
For further reading, open Effective Go and search the page for the word 'reference'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With