Golang – Concatenation Strings

Tram Ho

  • This article helps to write function to concatenate string array string -> string in the most optimal way.
  • Usually when writing a function to convert from array string to a string , most golang devs will write.

  • The writing is not optimal, in golang when concatenating the string will not reuse the variable s but always create a new memory area in memory.
  • For optimization, there are 2 ways to write the template:

Way 1

  • (1): create a strings.Builder
  • (2): string concatenation
  • (3): return result

Way 2

  • (1): loop each string to count the total number bytes .
  • (2): create capacity, Grow can panics , be careful when using.

Benchmark

  • create file main_test.go , copy the code below.

  • execute the command:



Share the news now

Source : Viblo