duanhuiuw12555 2013-01-17 20:42
浏览 126
已采纳

切片后释放字符串以进行垃圾回收的正确方法

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.

"(As an aside, there is a well-known gotcha in Java and other languages that when you slice a string to save a small piece, the reference to the original keeps the entire original string in memory even though only a small amount is still needed. Go has this gotcha too. The alternative, which we tried and rejected, is to make string slicing so expensive—an allocation and a copy—that most programs avoid it.)"

So if we have a very long string:

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

And we take a small slice:

newS := s[5:9]

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?

I thought maybe this:

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

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

  • 写回答

2条回答 默认 最新

  • dongmaomou4117 2013-01-17 20:55
    关注

    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

    Edit: 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: 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序