总结
io.WriteString > File.WriteString > ioutil.WriteFile > Write.WriteString
4.99M txt文档性能测试如下:
io.WriteString
func WriteString(w Writer, s string) (n int, err error)
package main
import (
"fmt"
"io"
"os"
)
func main() {
f, err := os.OpenFile(
"C:/Users/Administrator/Downloads/test.txt",
os.O_RDWR|os.O_CREATE,
0777)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
_, err = io.WriteString(f, "测试文本")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("write successful")
}
*File.WriteString
func (f *File) WriteString(s string) (n int, err error)
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.OpenFile(
"C:/Users/Administrator/Downloads/test.txt",
os.O_RDWR|os.O_CREATE,
0777)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
f.WriteString("测试文本")
fmt.Println("write successful")
}
ioutil.WriteFile
unc WriteFile(filename string, data []byte, perm os.FileMode) error
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
err := ioutil.WriteFile(
"C:/Users/Administrator/Downloads/test.txt",
[]byte("测试文本"),
0777)
if err != nil {
fmt.Println(err)
}
fmt.Println("write successful")
}
*Write.WriteString
func (b *Writer) WriteString(s string) (int, error)
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.OpenFile(
"C:/Users/Administrator/Downloads/test.txt",
os.O_RDWR|os.O_CREATE,
0777)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
writer := bufio.NewWriter(f)
_, err = writer.WriteString("测试文本")
if err != nil {
fmt.Println(err)
return
}
writer.Flush()
fmt.Println("write successful")
}