总结

io.WriteString > File.WriteString > ioutil.WriteFile > Write.WriteString
4.99M txt文档性能测试如下:
image.pngimage.pngimage.pngimage.png

io.WriteString

func WriteString(w Writer, s string) (n int, err error)

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. )
  7. func main() {
  8. f, err := os.OpenFile(
  9. "C:/Users/Administrator/Downloads/test.txt",
  10. os.O_RDWR|os.O_CREATE,
  11. 0777)
  12. if err != nil {
  13. fmt.Println(err)
  14. return
  15. }
  16. defer f.Close()
  17. _, err = io.WriteString(f, "测试文本")
  18. if err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. fmt.Println("write successful")
  23. }


*File.WriteString

func (f *File) WriteString(s string) (n int, err error)

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. f, err := os.OpenFile(
  8. "C:/Users/Administrator/Downloads/test.txt",
  9. os.O_RDWR|os.O_CREATE,
  10. 0777)
  11. if err != nil {
  12. fmt.Println(err)
  13. return
  14. }
  15. defer f.Close()
  16. f.WriteString("测试文本")
  17. fmt.Println("write successful")
  18. }

ioutil.WriteFile

unc WriteFile(filename string, data []byte, perm os.FileMode) error

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. )
  7. func main() {
  8. err := ioutil.WriteFile(
  9. "C:/Users/Administrator/Downloads/test.txt",
  10. []byte("测试文本"),
  11. 0777)
  12. if err != nil {
  13. fmt.Println(err)
  14. }
  15. fmt.Println("write successful")
  16. }


*Write.WriteString

func (b *Writer) WriteString(s string) (int, error)

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. f, err := os.OpenFile(
  9. "C:/Users/Administrator/Downloads/test.txt",
  10. os.O_RDWR|os.O_CREATE,
  11. 0777)
  12. if err != nil {
  13. fmt.Println(err)
  14. return
  15. }
  16. defer f.Close()
  17. writer := bufio.NewWriter(f)
  18. _, err = writer.WriteString("测试文本")
  19. if err != nil {
  20. fmt.Println(err)
  21. return
  22. }
  23. writer.Flush()
  24. fmt.Println("write successful")
  25. }