英文:
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语言如何管理str1
和str2
的内存?在整个程序运行期间,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"字面量的地址,而str2
在createString
函数运行时会被初始化为指向"Another string"的地址。str1
和str2
都只包含一个指针和长度,所以它们不会占用太多内存。
简而言之,你无法根据初始化字符串的位置来节省内存,因为占用大部分内存的是字符串字面量,而不是字符串变量。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论