本文介绍了切片后释放字符串以进行垃圾回收的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此转到数据结构文章,在字符串部分下,指出截取字符串的一部分会将原始字符串保留在内存中.

According to this Go Data Structures article, under the Strings section it states that taking a slice of a string will keep the original string in memory.

所以,如果我们有一个很长的字符串:

So if we have a very long string:

s := "Some very long string..."

然后我们切一小段:

newS := s[5:9]

在我们也发布newS之前,不会发布原始的s.考虑到这一点,如果我们需要长期保存newS却释放s进行垃圾收集,应该采取什么适当的方法?

The original s will not be released until we also release newS. Considering this, what is the proper approach to take if we need to keep newS long term, but release s for garbage collection?

我想也许是这样

newS := string([]byte(s[5:9]))

但是我不确定这是否真的有效,或者是否有更好的方法.

But I wasn't certain if that would actually work, or if there's a better way.

推荐答案

是的,转换为字节片将创建字符串的副本,因此不再引用原始字符串,并且可以在行下的某个地方进行GC存储.

Yes, converting to a slice of bytes will create a copy of the string, so the original one is not referenced anymore, and can be GCed somewhere down the line.

作为对此的证明"(嗯,它证明了字节片与原始字符串不共享相同的基础数据):

As a "proof" of this (well, it proves that the slice of bytes doesn't share the same underlying data as the original string):

http://play.golang.org/p/pwGrlETibj

并证明字节片仅具有必要的长度和容量(换句话说,其容量不等于原始字符串的容量):

and proof that the slice of bytes only has the necessary length and capacity (in other words, it doesn't have a capacity equal to that of the original string):

http://play.golang.org/p/3pwZtCgtWv

Edit2:您可以清楚地看到内存配置文件发生了什么.在reuseString()中,使用的内存非常稳定.在copyString()中,它增长很快,显示了通过[] byte转换完成的字符串的副本.

And you can clearly see what happens with the memory profiling. In reuseString(), the memory used is very stable. In copyString(), it grows fast, showing the copies of the string done by the []byte conversion.

http://play.golang.org/p/kDRjePCkXq

这篇关于切片后释放字符串以进行垃圾回收的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:01