gpt4 book ai didi

go - zip.NewReader(bytes.NewReader(), len) 是否需要关闭或自动收集垃圾?

转载 作者:IT王子 更新时间:2023-10-29 00:45:53 25 4
gpt4 key购买 nike

我正和一个 friend 争论 Go 中可能浪费的资源。

如果 Reader 在内存中的字节数组上运行,是否必须关闭它?

func readJar(zipBytes []byte, readMeta bool) (m jar.Manifest, err error) {
reader, err := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes)))
if err != nil {
return
}

for _, file := range reader.File {
switch file.Name {
case jar.ManifestPath:
m, err = readManifest(file)
if err != nil {
return
}
}
}
return
}

func readManifest(file *zip.File) (jar.Manifest, error) {
reader, err := file.Open()
if err != nil {
return nil, err
}

defer reader.Close()
return jar.ReadManifest(reader)
}

虽然最初它被认为是文件句柄泄漏的来源,但其他原因却引起了指责。

这会泄漏内存吗,或者 Go 是否有足够的逃逸分析/垃圾收集来解决问题?

最佳答案

Golang 编译器会处理 unreachable variables :-

The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function's stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.

虽然Golang包含垃圾回收。最好使用清理功能。您可以使用 defer 函数在函数结束时关闭文件。

defer f.close()

检查 SetFinalizer 的文档加深对这些概念的理解:

func SetFinalizer(obj interface{}, finalizer interface{})

SetFinalizer sets the finalizer associated with obj to the provided finalizer function. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs finalizer(obj) in a separate goroutine. This makes obj reachable again, but now without an associated finalizer. Assuming that SetFinalizer is not called again, the next time the garbage collector sees that obj is unreachable, it will free obj.

终结器运行对象以检查它是否无法从源访问。它可用于文件描述符,但依赖终结器来刷新内存中的 I/O 缓冲区(如 bufio.Writer)是错误的,因为缓冲区不会在程序退出时刷新。

关于go - zip.NewReader(bytes.NewReader(), len) 是否需要关闭或自动收集垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51261162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com