0

OK we already have the answer that StringBuilder should be used to concatenate strings in go:

How to efficiently concatenate strings in Go?

Now, I am reviewing a PR. There is this code:

const CustomerID [32]byte

const paymentPrefix = "payment_done_"
const sentPrefix = "invoice_sent_"
const receivedPrefix = "invoice_received_"

 
func paymentKey(customer CustomerID) string {
   return paymentPrefix + customer.String()
}

// same for the other two Key

I am wondering if I should request to use StringBuilder here

func paymentKey(customer CustomerID) string {
  var str string.Builder
  str.WriteString(paymentPrefix)
  str.Write(customer)
  return str.String()
}

It is a 32 byte ID which first needs to be converted to string and then concatenated with +

These are only two strings but potentially called a lot, that is why I think it is justified to question concatenation.

transient_loop
  • 5,984
  • 15
  • 58
  • 117
  • 3
    Judging by the names you use here, I don't think it's justified to make it more complex than a simple `+`. Use `StringBuilder` if you have to add something to the string repeatedly. Don't over-optimize. Switch to `StringBuilder` if this proves to be a performance issue. – icza Jul 26 '19 at 20:54
  • sounds reasonable @icza, thanks – transient_loop Jul 26 '19 at 21:08
  • customer.String() construction expect that method String() would be implemented for type CustomerID. Can you be more precise. Also you use non UTF8 encoding in your snippet that is at least strange, – Uvelichitel Jul 26 '19 at 21:34
  • 1
    @faboolous: "we already have the answer that StringBuilder should be used to concatenate strings in go". No we don't, it depends. The results are in for my first round of benchmarks: 61.4 ns/op for your Builder, 48.2 ns/op for your concatenation, 34.3 ns/op for my Builder, and 27.9 ns/op for my optimization. – peterSO Jul 26 '19 at 22:32

0 Answers0