I’m a beginner that studied 2 books about Go, and I’d say I know the coding a bit. But something that I still struggle with (also from a confidence standpoint) is choosing amongst different options.
Say for instance I want to reverse a string. I found/wrote at least 3 ways to do that today:
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func reverseString2(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
Good question. But I don’t really know. I don’t expect the speed of the three options to be very different. The same for the memory. So I’d suspect that ease of programming outweighs those other factors?
Ah I didn’t knew that. Thanks. Are the []rune arrays (and their operations) from the first two options are much more expensive than calling two additional methods? (DecodeRuneInString(), EncodeRune()).
The third option is indeed quicker as @badu already knew. The first and second option are the same.
So from a performance perspective the third option is not good. But from a code readability I think this option is most difficult. So the ease of programming that Yamil pointed out is less good.
Indeed, you should prefer readability over performance, until you are being asked to improve it. However, when being asked to improve performance, one should know which is the pedal-to-the-metal