I am trying to figure out the use of strings.Join method compared to regular concatenation with +=.
For this comparison, I am using both methods on os.Args as the list of strings to concatenate.
My code for the concatenating functions is:
func regular_concatenation() {
var s, sep string
for i := 1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
}
func join_concatenation() {
fmt.Println(strings.Join(os.Args, " "))
}
And the main function for the performance check is:
func main() {
var end_1, end_2 float64
var start_1, start_2 time.Time
start_1 = time.Now()
for i:=0; i < 100; i++ {
ex1_3_join_concatenation()
}
end_1 = time.Since(start_1).Seconds()
start_2 = time.Now()
for i:=0; i < 100; i++ {
ex1_3_regular_concatenation()
}
end_2 = time.Since(start_2).Seconds()
fmt.Println(end_1)
fmt.Println(end_2)
}
Problem is - when I run the code, say with 20 arguments (os.Args), I get the result that the strings.Join method is slower than the regular concatination.
This is confusing for me, because the way I understood it - when using regular += method, it creates a new string reference each time (because strings are immutable in golang), therefore the garbage collector is supposed to run in order to collect the unused data and this wastes time.
So the question is - is strings.Join really a faster method? And if it is - what am I doing wrong in this example?