Go: Seek+Write vs WriteAt 性能比较

huangapple go评论86阅读模式
英文:

Go: Seek+Write vs WriteAt performance

问题

我刚开始学习Go的文件系统操作。似乎至少有两种方法可以进行随机文件写入:

// 1. 首先设置偏移量,然后写入数据
f.Seek(offset, whence)
f.Write(data)
 
// 2. 一步完成按偏移量写入
f.WriteAt(data, offset)

所有三个函数(SeekWriteWriteAt)都是使用不同的系统调用实现的:在Unix系统上,Write是通过syscall.Write实现的,而WriteAt内部使用了syscall.Pwrite

由于Seek+Write执行了两个系统调用,而WriteAt只需要一个系统调用,所以为了更好的性能,第二种方法是否更好?

英文:

I've just started to study Go's filesystem operations. It seems like there are at least two ways to perform random file writes:

// 1. First set the offset, then write data 
f.Seek(offset, whence)
f.Write(data)
 
// 2. Write by offset in one step
f.WriteAt(data, offset)

All of three functions (Seek, Write, WriteAt) are implemented with the use of different syscalls: on Unix systems Write is implemented via syscall.Write and WriteAt has syscall.Pwrite inside.

Since Seek+Write perform two syscalls, whereas WriteAt requires only one syscall, should the second method be preferred for the sake of better performance?

答案1

得分: 2

seek()+read()seek()+write()都是一对系统调用,而pread()pwrite()是单个系统调用。较少的系统调用意味着更高的效率。

你可以选择使用WriteAt

英文:

seek()+read() and seek() + write() are both a pair of sys-calls while pread() and pwrite() are single sys-calls. Less sys-calls - more efficiency.

You can definitly go for the WriteAt

huangapple
  • 本文由 发表于 2017年1月22日 00:41:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/41781840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定