英文:
High memory usage for a simple Go program
问题
package main
import "fmt"
func main() {
var num int8
fmt.Scanln(&num)
for ; num != 42; fmt.Scanln(&num) {
fmt.Println(num)
}
}
英文:
The simplest question in Codechef is reading from input and writing to output as long as the number isn't 42. I wrote the following code:
package main
import "fmt"
func main() {
var num int8
fmt.Scanln(&num)
for ; num != 42; fmt.Scanln(&num) {
fmt.Println(num)
}
}
It is accepted, though uses 124.6M memory according to the site. I wrote basically the same thing in C and it took 1.6M, I'm confused. Do you know what may have caused this?
I'm new to Go. It may be a bold mistake.
答案1
得分: 7
我没有检查,但我怀疑你的程序使用了124+ MB的内存。我不知道你从哪里得到这个数字,但我猜你可能混淆了分配的虚拟内存和“已使用内存”。这两个数字可能接近,也可能不接近。
Go通过操作系统保留了一个大的内存区域,但只有在Go运行时实际分配了进一步的内存之后,它才是“已使用内存”。在大多数系统上,未使用的虚拟内存不会占用实际内存,因此基本上是免费的。
英文:
I didn't check, but I doubt your program uses 124+ MB of memory. I don't know where you got this number from, but I guess you're confusing allocated virtual memory and "used memory". Those two figures may be close to each other or not.
Go reserves a large memory area through the OS, but it's not "used memory" until actually further allocated by the Go runtime. Unclaimed virtual memory costs no real memory on most systems so is essentially free.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论