一个简单的Go程序的内存使用率很高

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

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.

huangapple
  • 本文由 发表于 2013年7月20日 22:22:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/17763172.html
匿名

发表评论

匿名网友

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

确定