Entrambe le risposte (OneOfOne e Denys Séguret) siano corrette. Volevo solo mostrare la differenza di prestazioni tra di loro (che è davvero evidente quando la stringa è grande).
Si scopre che utilizzando str [: indice] + stringa (sostituzione) + str [indice + 1:] è molto più veloce.
Quindi il punto di riferimento:
package main
import (
"testing"
)
func replaceAtIndex1(str string, replacement rune, index int) string {
out := []rune(str)
out[index] = replacement
return string(out)
}
func replaceAtIndex2(str string, replacement rune, index int) string {
return str[:index] + string(replacement) + str[index+1:]
}
func generateString(n int) string{
s := ""
for i := 0; i < n; i++{
s += "a"
}
return s
}
func BenchmarkSmall1(b *testing.B) {
n := 10
str, index, replacement := generateString(n), n/2, 'B'
b.ResetTimer()
for i := 0; i < b.N; i++ {
replaceAtIndex1(str, replacement, index)
}
}
func BenchmarkSmall2(b *testing.B) {
n := 10
str, index, replacement := generateString(n), n/2, 'B'
b.ResetTimer()
for i := 0; i < b.N; i++ {
replaceAtIndex2(str, replacement, index)
}
}
func BenchmarkMedium1(b *testing.B) {
n := 100
str, index, replacement := generateString(n), n/2, 'B'
b.ResetTimer()
for i := 0; i < b.N; i++ {
replaceAtIndex1(str, replacement, index)
}
}
func BenchmarkMedium2(b *testing.B) {
n := 100
str, index, replacement := generateString(n), n/2, 'B'
b.ResetTimer()
for i := 0; i < b.N; i++ {
replaceAtIndex2(str, replacement, index)
}
}
func BenchmarkBig1(b *testing.B) {
n := 10000
str, index, replacement := generateString(n), n/2, 'B'
b.ResetTimer()
for i := 0; i < b.N; i++ {
replaceAtIndex1(str, replacement, index)
}
}
func BenchmarkBig2(b *testing.B) {
n := 10000
str, index, replacement := generateString(n), n/2, 'B'
b.ResetTimer()
for i := 0; i < b.N; i++ {
replaceAtIndex2(str, replacement, index)
}
}
func main(){}
mostra i seguenti risultati (grazie Thomasz per avvistare un errore di copypasting):
BenchmarkSmall1-4 10000000 228 ns/op
BenchmarkSmall2-4 10000000 126 ns/op
BenchmarkMedium1-4 500000 2091 ns/op
BenchmarkMedium2-4 10000000 190 ns/op
BenchmarkBig1-4 10000 209232 ns/op
BenchmarkBig2-4 500000 3629 ns/op
c'è qualche vantaggio in questo '' strings.Join'? – Ferguzz