Reputation: 1690
As an example:
for {
myData := <-myChan
buf := new(bytes.Buffer)
encoder := gob.NewEncoder(buf)
err := encoder.Encode(myData)
...
I could put buf := new(...
above the for loop to save processor and maybe some memory, but will that cause any problems? Examples I see have the new
in the loop.
Edit: for the case above, the encoder could go above the for loop to, so why doesn't it (in examples I've seen)?
Upvotes: 0
Views: 123
Reputation: 273386
The idiomatic Go style would be to write the clearest code possible as long as it solves the problem at hand within its time and space constraints.
In other words, I wouldn't worry about the efficiency here because:
If you find out that the allocation takes a considerable portion of each loop iteration, then @peterSO's answer below is a good pattern on how to reuse a bytes.Buffer
by calling its Reset
method.
Upvotes: 0
Reputation: 166569
I would expect to reuse the buffer:
buf := new(bytes.Buffer)
for {
buf.Reset()
//...
}
Upvotes: 7