英文:
Go: Seek+Write vs WriteAt performance
问题
我刚开始学习Go
的文件系统操作。似乎至少有两种方法可以进行随机文件写入:
// 1. 首先设置偏移量,然后写入数据
f.Seek(offset, whence)
f.Write(data)
// 2. 一步完成按偏移量写入
f.WriteAt(data, offset)
所有三个函数(Seek
,Write
,WriteAt
)都是使用不同的系统调用实现的:在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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论