// WriteString writes the contents of the string s to w, which accepts a slice of bytes.
// If w implements a WriteString method, it is invoked directly.
// Otherwise, w.Write is called exactly once.
func WriteString(w Writer, s string) (n int, err error) {
if sw, ok := w.(stringWriter); ok {
return sw.WriteString(s)
}
return w.Write([]byte(s))
}
Pro informaci, když v GoDoc kliknete na název typu/funkce/metody, otevře se vám zdrojový soubor v místě definice daného typu/funkce/metody.
ty benchmarky jsem hodil sem, at to nemusite opisovat (taby atd...):
https://github.com/tisnik/go-root/blob/master/benchmarks/byte_output/io_write_string.go
https://github.com/tisnik/go-root/blob/master/benchmarks/byte_output/write_method.go
Při zápisu do souborů (s flushem) to vychází prakticky stejně. Připadá mi, že io.WriteString je nekdy nepatrně pomalejší, ale to je problém microbenchmarků - nedávají moc konzistentní data.
Benchmarky:
package main
import (
"bufio"
"bytes"
//"io"
"os"
"time"
)
func main() {
length := 100000000
var buffer bytes.Buffer
for i := 0; i < length; i++ {
buffer.WriteString("abc\n")
}
data := buffer.String()
f, _ := os.Create("/tmp/d1")
defer f.Close()
t1 := time.Now()
writer := bufio.NewWriter(f)
writer.Write([]byte(data))
writer.Flush()
elapsed := time.Since(t1)
println(elapsed)
}
package main
import (
"bufio"
"bytes"
"io"
"os"
"time"
)
func main() {
length := 100000000
var buffer bytes.Buffer
for i := 0; i < length; i++ {
buffer.WriteString("abc\n")
}
data := buffer.String()
f, _ := os.Create("/tmp/d2")
defer f.Close()
t1 := time.Now()
writer := bufio.NewWriter(f)
io.WriteString(writer, data)
writer.Flush()
elapsed := time.Since(t1)
println(elapsed)
}