Is it bad practice to redeclare slices in every loop iteration?

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

Answers (2)

Eli Bendersky
Eli Bendersky

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:

  1. The compiler can do clever optimizations that would remove any differences
  2. Almost certainly if there are differences, they are negligible

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

peterSO
peterSO

Reputation: 166569

I would expect to reuse the buffer:

buf := new(bytes.Buffer)
for {
    buf.Reset()
    //...
}

Upvotes: 7

Related Questions