Re:Optimizing Go string operations with practical examples
by masklinn on Sunday December 03, 2023 @07:42AM
(#38506662)
OTOH note that this optimisation can be bundled into a helper function so it's not quite as bad as some others. In fact the helper function is in the stdlib: https://pkg.go.dev/strings#Cut
This is most useful for the "split once" version, which is genuinely improved:
The iteration is worse, but not to an irredeemable degree,
rounds := strings.Split(game, "; ")
isPossible := false
for _, round := range rounds {
red, green, blue := findScores(round)
if isRoundPossible(red, green, blue) {
isPossible = true
} else {
isPossible = false
// If only one round is not possible, there is
// no need to process the other ones.
break
}
}
becomes:
isPossible := false
for {
round, tail, hasNext := strings.Cut(game, ";")
game = tail
red, green, blue := findScores(round)
if isRoundPossible(red, green, blue) {
isPossible = true
} else {
isPossible = false
// If only one round is not possible, there is
// no need to process the other ones.
break
}
if !hasNext {
break
}
}
This is most useful for the "split once" version, which is genuinely improved:
becomes The iteration is worse, but not to an irredeemable degree, becomes: