Golang:在使用`const`/`var`和在函数中时,内存是如何分配的?

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

Golang: How is memory allocated when using `const`/`var` vs in a function?

问题

我将为您翻译以下内容:

我正在寻求关于Go语言中内存分配/管理的清晰解释。请看以下示例代码:

package main

// 内存在程序启动时分配?
var str1 = "Hello world!"

func createString() string {
  // 内存在函数调用时分配?
  var str2 = "Another string"
  return str2
}

在这个示例代码中,Go语言如何管理str1str2的内存?在整个程序运行期间,str1的值是否一直存在于内存中?

如果我将字符串变量声明在函数作用域内,而不是声明为全局变量,是否可以节省整个程序的内存使用量?

英文:

I'm looking for clarity on how memory is allocated/managed in Go. See example:

package main

// memory allocated on program startup?
var str1 = "Hello world!"

func createString() string {
  // memory allocated when function is called?
  var str2 = "Another string"
  return str2
}

In this example code, how does Go manage the memory of str1 and str2? Does the value of str1 hang out in memory during the entire runtime of the program?

Can I save on overall program memory usage if I declare string variables inside of function scopes rather than declaring them as global variables?

答案1

得分: 2

字符串字面量"Hello world!"和"Another string"无论你如何声明变量,它们都会存在于内存中。str1在main函数开始之前会被初始化为指向"Hello world"字面量的地址,而str2createString函数运行时会被初始化为指向"Another string"的地址。str1str2都只包含一个指针和长度,所以它们不会占用太多内存。

简而言之,你无法根据初始化字符串的位置来节省内存,因为占用大部分内存的是字符串字面量,而不是字符串变量。

英文:

The string literals "Hello world!" and "Another string" will be in memory no matter how you declare the variables. The str1 will be initialized to point to "Hello world" literal before main starts, and str2 will be initialized to point to "Another string" when createString runs. Both str1 and str2 only contain a pointer and length, so they do not consume much memory.

In short, you cannot save memory based on where you initalize a string using a literal. The literal is what occupies most of the memory, not the string variable.

huangapple
  • 本文由 发表于 2022年8月25日 03:10:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/73478486.html
匿名

发表评论

匿名网友

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

确定