循环中的变量会被垃圾回收还是会保留在内存中?

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

Do variables in a loop get garbage collected or do they stay in memory?

问题

这段代码中的变量在循环结束后会被垃圾回收,所以不会永远在内存中存在。如果你想更高效地处理,只需要在将int转换为string并追加到byte之后,及时释放sSteamId变量的内存。

以下是修改后的代码示例:

for _, id := range steamIds {
    sSteamId := strconv.Itoa(id)
    requestURI = append(requestURI, ","+sSteamId...)
    // 在这里添加代码,手动释放 sSteamId 变量的内存
    sSteamId = ""
}

通过将sSteamId变量设置为空字符串,可以让垃圾回收器更早地回收该变量所占用的内存空间。这样可以更有效地管理内存。

英文:

Does the variable in this bit of code get garbage collected after the loop finishes or do I have X amount of sSteamId variables floating in memory forever?

If it does, how can I do this more efficiently? I only need sSteamId long enough to convert an int to a string and then append it to a byte, then it's no longer needed

for _, id := range steamIds {
        sSteamId := strconv.Itoa(id)
        requestURI = append(requestURI, ","+sSteamId...)
}

答案1

得分: 2

他们将被垃圾回收,因为每次迭代时对它们的引用都会丢失。

英文:

They'll get GC'd as any references to them are lost with each iteration.

huangapple
  • 本文由 发表于 2015年8月19日 11:07:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/32085892.html
匿名

发表评论

匿名网友

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

确定