본문 바로가기
프로그래밍/Go언어

Golang의 fmt.Print는 heap으로 간다?

by Hwan2 2021. 5. 23.
728x90
반응형

 

 

 

Golang에는 fmt라는 패키지가 있습니다.

 

그리고 fmt.Print 를 사용하여 사용자에게 출력해주죠.

하지만 fmt를 사용하여 변수를 출력하면 해당 변수는 stack에서 heap으로 가버리게 됩니다.

 

다음 예시를 봅시다.

 

package main

import "fmt"

func main() {
	i := 10
	fmt.Println(i)
}
$ go build -gcflags '-m' struct.go
# command-line-arguments
.\struct.go:7:13: inlining call to fmt.Println
.\struct.go:7:13: i escapes to heap
.\struct.go:7:13: []interface {}{...} does not escape
<autogenerated>:1: .this does not escape
<autogenerated>:1: .this does not escape

해당 fmt는 변수 i를 heap으로 보내는걸 확인할 수 있습니다.

 

golang홈페이지에서의 fmt 구조는 다음과 같습니다.

 

func Println (a ... interface {}) (n int , err error )

즉, 매개변수를 interface {} 형태로 받는데, 이렇게 받을 때 fmt에서는 해당 매개변수를 사용자가 정의한 변수라 판단하여 이를 heap에 할당하게 되는 것입니다.

즉, "Variadic 함수"이므로 모든 인수가 힙으로 이스케이프됩니다. 

 

 

때문에 이를 방지하기 위해선

내장 함수인 println을 사용하거나, strings.Builder() 를 사용하면 됩니다.

 

하지만, 메모리를 정말 빡세게 관리하면서 퍼포머스에 초점을 둘게 아니라면, 굳이 신경쓸 필요는 없을 것 같긴합니다.

 

 

참고

https://www.reddit.com/r/golang/comments/badeql/golang_memory_escape_analysis_is_naive/

 

golang memory escape analysis is naive?

```go package main import ( "fmt" "time" ) func main() { for i := 0; i < 5; i++ { fmt.Println("outer: ", i) go func(j...

www.reddit.com

https://stackoverflow.com/questions/65874745/mix-print-and-fmt-println-and-stack-growing

 

Mix print and fmt.Println and stack growing

I'm watching lectures about Go. One about stack growing with this example: package main import "fmt" const size = 1024 func main() { fmt.Println("Start") s:= "HE...

stackoverflow.com

https://stackoverflow.com/questions/64997017/go-variables-escape-to-the-heap-when-using-the-add-operator-to-concatenate-strin

 

Go variables escape to the heap when using the add operator to concatenate strings

Question about this code . why variables escape to heap func main() { port := "8080" host := "localhost:" connection := host + port fmt.Println(connection) } go...

stackoverflow.com

 

 

 

 

반응형

댓글


스킨편집 -> html 편집에서