1GB짜리 로그 파일을 한 줄씩 읽으면서 줄마다 19바이트짜리 ID 하나만 모았다. 20만 줄이니 ID를 다 합쳐도 4MB가 안 되고, 문자열 헤더까지 더해도 8MB쯤이다. 그런데 다 읽고 GC를 돌린 뒤에도 힙에 1GB가 그대로 남았다.
원인: 줄에서 잘라 낸 문자열은 원래 줄의 메모리를 그대로 가리킨다. 그래서 GC가 줄 전체를 지우지 못한다.
해결: 오래 보관할 조각은 strings.Clone으로 복사한다.
1. 재현
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64*1024), 16<<20) // 기본 한도 64KiB보다 긴 줄도 읽는다
var ids []string
for sc.Scan() {
line := sc.Text() // 한 줄, 약 5KB
ids = append(ids, field(line, "id")) // 그중 19바이트만 보관
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
runtime.GC()
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("heap after GC: %.1f MiB\n", float64(m.HeapAlloc)/(1<<20))
runtime.KeepAlive(ids) // 측정이 끝날 때까지 ids를 살려 둔다
field는 "id":" 뒤의 값을 line[i:j]로 잘라 돌려주는 함수다. 보관하는 코드 한 줄만 바꿔서 비교했다.
ids = append(ids, strings.Clone(field(line, "id")))
| GC 후 힙 | 최대 메모리 사용량 | |
| 잘라서 보관 | 1,029.1MiB | 1,119MB |
strings.Clone으로 복사 |
8.3MiB | 약 29MB |
(Go 1.27.4, macOS arm64, 20만 줄, 줄당 5,072바이트)
줄이 길수록 차이가 커진다. 입력을 약 1GB로 맞추고 줄 크기만 바꿔 쟀다.

2. 원인: 원본을 가리키는 잘라 낸 문자열
Go 문자열은 데이터의 주소와 길이만 담은 작은 값이다(64비트 기준 16바이트). line[i:j]는 바이트를 복사하지 않는다. 원래 줄의 중간을 가리키는 주소와 길이만 새로 만든다.
GC는 sc.Text()가 한 번에 할당한 줄 하나를 한 덩어리로 다룬다. 그 덩어리 안쪽을 가리키는 주소가 하나라도 남아 있으면 줄 전체가 살아남는다. 19바이트를 보관하면 약 5KB짜리 줄이 통째로 남고, 20만 줄이면 1GB다.

strings.Clone은 19바이트를 새 메모리에 복사한다. 그러면 원래 줄을 가리키는 주소가 사라지고, GC가 줄을 지울 수 있다.
3. 원본을 붙잡는 코드
같은 방식으로 하나씩 실행해서 확인했다.
| 코드 | 결과 |
s[i:j], strings.TrimSpace, Split, Fields, Cut |
붙잡는다 |
regexp의 FindString, FindStringSubmatch |
붙잡는다 |
바꿀 것이 없으면 입력을 그대로 돌려주는 함수 (예: 이미 소문자인 문자열에 strings.ToLower) |
붙잡는다 |
encoding/csv의 필드 |
붙잡는다 (레코드 전체) |
bytedance/sonic 기본 설정 (v1.12~v1.15) |
붙잡는다 |
strings.Clone(s[i:j]), string(b[i:j]) |
복사한다 |
encoding/json (직접 만든 UnmarshalJSON 제외) |
복사한다 |
sonic.ConfigStd |
복사한다 |

빠른 JSON 라이브러리로 많이 쓰는 sonic은 기본 설정에서 이스케이프 문자가 없는 문자열 값이 입력 버퍼를 그대로 가리킨다. sonic README에도 이 때문에 JSON 버퍼 전체가 메모리에 남을 수 있다고 적혀 있다. 값을 복사하는 CopyString 옵션이 켜진 sonic.ConfigStd를 쓰면 풀린다.
4. 찾는 방법
먼저 GC 로그를 켜 보자.
$ GODEBUG=gctrace=1 ./pin -mode sub big.jsonl
gc 10 @0.289s 0%: ... 1035->1035->1029 MB, 1595 MB goal, ... (forced)
A->B->C MB의 마지막 숫자 C가 GC 뒤에 살아 있는 힙이다. GC가 돌았는데 1GB가 그대로면 지울 수 있는 메모리가 없다는 뜻이다. 복사한 쪽은 이 숫자가 8MB였다.
다음은 힙 프로파일이다. 부록의 pin.go에 -heapprof를 주고 실행한 결과다.
$ go tool pprof -sample_index=inuse_space -top pin heap.pprof
flat flat% sum% cum cum%
1022.73MB 99.56% 99.56% 1022.73MB 99.56% bufio.(*Scanner).Text (inline)
3.53MB 0.34% 99.90% 1026.26MB 99.90% main.main
프로파일은 메모리를 할당한 곳을 보여 준다. 여기서는 줄을 만드는 sc.Text()다. 그 메모리를 붙잡고 있는 코드는 보여 주지 않는다. 줄을 만드는 곳이 메모리를 거의 다 차지하는데 프로그램은 작은 값만 보관한다면, 잘라 낸 문자열을 의심하자.
5. GOMEMLIMIT의 한계
메모리 한도를 주면 GC가 더 자주 돌 뿐이다. GOMEMLIMIT=256MiB로 실행해도 GC 후 힙은 1,029MiB 그대로였다. GC 횟수는 9번에서 228~270번으로, 사용자 CPU 시간은 17~19배로 늘었다. 붙잡힌 메모리는 아직 쓰는 중이라서 GC가 지울 수 없다. GOGC를 낮춰도 마찬가지였다.
6. 복사할 때와 하지 않을 때
19바이트 복사는 약 8~9ns와 작은 할당 한 번이면 된다.
보관할 값이 줄의 대부분이면 복사는 손해다. 5,072바이트 줄에서 5,000바이트를 보관하면 GC 후 힙은 1,029MiB로 똑같고, 최대 메모리만 15~30% 늘었다. 원래 줄이 GC에 지워지기 전에 같은 크기의 복사본이 하나 더 생기기 때문이다.
큰 문자열의 작은 조각을 오래 보관할 때만 복사하자. 같은 값이 많이 반복된다면 unique.Make(Go 1.23.2 이상)로 값마다 한 번만 저장하는 방법도 있다.
7. 실제 사례: 메모리 8GB를 1GB로 줄인 오픈소스 도구
이 문제는 직접 만든 오픈소스 도구 Leeway에서 만났다. Codex 사용 기록을 처음 읽을 때 메모리를 8GB 넘게 썼다. 직접 만든 JSON 해석기가 값을 줄에서 잘라 돌려주고 있었고, 해석한 줄을 전부 메모리에 올려 여러 번 훑고 있었다.
고친 방법은 두 가지다.
- 파일을 두 번 흘려 읽는다. 1차에서는 개수와 플래그만 모으고, 2차에서 실제 계산을 한다. 그 사이에 1차에서 읽은 부분이 바뀌면 CRC32 비교로 알아챈다.
- 2차에서는 해석기가 꺼낸 문자열을
strings.Clone으로 복사한다.

두 가지를 함께 고친 결과 최대 메모리 사용량은 8.1~8.4GB에서 1.06~1.12GB로 줄었다. 대신 파일을 두 번 읽어서, 가장 큰 파일 하나의 처리 시간은 3.2~3.3초에서 4.9초로 늘었다. 이전 코드를 테스트에 남겨 두고 두 방식의 해석 결과가 같은지 비교한다.
마치며
한 줄 요약: Go에서 큰 문자열의 작은 조각을 오래 보관할 때는 strings.Clone으로 복사하자. 잘라 낸 문자열은 원본 전체를 붙잡는다.
부록: 재현용 전체 코드
gen.go는 줄당 5,072바이트짜리 JSON Lines 파일을 만든다. pin.go는 줄마다 id만 보관하고 GC 후 힙을 출력한다. 둘 다 go run 파일이름으로 하나씩 실행한다.
go.mod
module substringdemo
go 1.24
gen.go
//go:build ignore
// gen writes a JSON Lines file in which every line is about 5 KB and carries a 19-byte id:
//
// {"id":"id-0000000000000000","type":"t07","score":123456789,"payload":"<random text>"}
//
// Usage:
//
// go run gen.go # 40,000 lines, about 200 MB -> data.jsonl
// go run gen.go -lines 200000 # about 1 GB
// go run gen.go -size 1024 -o 1k.jsonl
package main
import (
"bufio"
"flag"
"fmt"
"log"
"math/rand/v2"
"os"
)
func main() {
lines := flag.Int("lines", 40_000, "number of lines (200000 gives about 1 GB)")
size := flag.Int("size", 5072, "bytes per line, newline included")
out := flag.String("o", "data.jsonl", "output file")
flag.Parse()
f, err := os.Create(*out)
if err != nil {
log.Fatal(err)
}
w := bufio.NewWriterSize(f, 1<<20)
r := rand.New(rand.NewPCG(1, 2)) // fixed seed: same file every time
const alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
payload := make([]byte, 0, *size)
var total int64
for i := 0; i < *lines; i++ {
head := fmt.Sprintf(`{"id":"id-%016d","type":"t%02d","score":%d,"payload":"`, i, r.IntN(30), r.IntN(1_000_000_000))
n := *size - len(head) - len(`"}`+"\n")
if n < 0 {
log.Fatalf("-size %d is too small", *size)
}
payload = payload[:0]
for j := 0; j < n; j++ {
payload = append(payload, alpha[r.IntN(len(alpha))])
}
w.WriteString(head)
w.Write(payload)
w.WriteString("\"}\n")
total += int64(*size)
}
if err := w.Flush(); err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
fmt.Printf("wrote %s: %d lines, %d bytes (%.0f MB)\n", *out, *lines, total, float64(total)/1e6)
}
pin.go
//go:build ignore
// pin reads a JSON Lines file line by line, keeps only the "id" of every line,
// and prints the live heap after a forced GC.
//
// go run pin.go -mode sub data.jsonl # keep line[i:j] -> the whole line stays alive
// go run pin.go -mode clone data.jsonl # keep strings.Clone(line[i:j]) -> only the id stays alive
// go run pin.go -mode sub -heapprof heap.pprof data.jsonl # also write a heap profile after the GC
package main
import (
"bufio"
"flag"
"fmt"
"log"
"os"
"runtime"
"runtime/pprof"
"strings"
)
// field returns the value of "key":"..." as a substring of line. It does not copy.
func field(line, key string) string {
k := `"` + key + `":"`
i := strings.Index(line, k)
if i < 0 {
return ""
}
i += len(k)
j := strings.IndexByte(line[i:], '"')
if j < 0 {
return ""
}
return line[i : i+j]
}
func main() {
mode := flag.String("mode", "sub", "sub | clone")
heapprof := flag.String("heapprof", "", "write a heap profile to this file after the GC")
flag.Parse()
if flag.NArg() != 1 || (*mode != "sub" && *mode != "clone") {
log.Fatal("usage: go run pin.go -mode sub|clone [-heapprof FILE] FILE")
}
f, err := os.Open(flag.Arg(0))
if err != nil {
log.Fatal(err)
}
defer f.Close()
sc := bufio.NewScanner(f)
// The default limit is 64 KiB per line. A longer line makes Scan return false,
// and only sc.Err() tells you that the loop stopped early.
sc.Buffer(make([]byte, 0, 64*1024), 16<<20)
var ids []string
var bytesRead int64
for sc.Scan() {
line := sc.Text() // a new string for every line
bytesRead += int64(len(line)) + 1
id := field(line, "id")
if *mode == "clone" {
id = strings.Clone(id)
}
ids = append(ids, id)
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
if len(ids) == 0 {
log.Fatal("no lines")
}
runtime.GC()
var m runtime.MemStats
runtime.ReadMemStats(&m)
if *heapprof != "" {
// The heap profile reports the state as of the most recent GC (the one above).
pf, err := os.Create(*heapprof)
if err != nil {
log.Fatal(err)
}
if err := pprof.WriteHeapProfile(pf); err != nil {
log.Fatal(err)
}
if err := pf.Close(); err != nil {
log.Fatal(err)
}
}
// Use ids after the measurement. If ids is dead at runtime.GC(),
// the compiler lets the GC free it and the heap looks almost empty.
keptBytes := 0
for _, id := range ids {
keptBytes += len(id)
}
fmt.Printf("mode=%s lines=%d read=%.0f MB kept=%d bytes (%s ... %s)\n",
*mode, len(ids), float64(bytesRead)/1e6, keptBytes, ids[0], ids[len(ids)-1])
fmt.Printf("heap after GC: HeapAlloc=%.1f MiB HeapInuse=%.1f MiB NumGC=%d\n",
float64(m.HeapAlloc)/(1<<20), float64(m.HeapInuse)/(1<<20), m.NumGC)
}
실행 방법이다. gen.go의 기본값은 약 200MB이고, -lines 200000을 주면 약 1GB다.
go run gen.go # data.jsonl, 약 200MB
go run pin.go -mode sub data.jsonl
go run pin.go -mode clone data.jsonl
go run gen.go -lines 200000 -o big.jsonl # 약 1GB
go build -o pin pin.go
./pin -mode sub big.jsonl
./pin -mode clone big.jsonl
GODEBUG=gctrace=1 ./pin -mode sub big.jsonl 2>&1 | grep '^gc' | tail -1
./pin -mode sub -heapprof heap.pprof big.jsonl
go tool pprof -sample_index=inuse_space -top pin heap.pprof
/usr/bin/time -l ./pin -mode sub big.jsonl # macOS: peak memory footprint
rm data.jsonl big.jsonl heap.pprof
실행 결과다(Go 1.27.4, macOS arm64).
$ go version
go version go1.27.4 darwin/arm64
$ go run gen.go
wrote data.jsonl: 40000 lines, 202880000 bytes (203 MB)
$ go run pin.go -mode sub data.jsonl
mode=sub lines=40000 read=203 MB kept=760000 bytes (id-0000000000000000 ... id-0000000000039999)
heap after GC: HeapAlloc=206.0 MiB HeapInuse=209.5 MiB NumGC=8
$ go run pin.go -mode clone data.jsonl
mode=clone lines=40000 read=203 MB kept=760000 bytes (id-0000000000000000 ... id-0000000000039999)
heap after GC: HeapAlloc=1.8 MiB HeapInuse=2.1 MiB NumGC=70
$ go run gen.go -lines 200000 -o big.jsonl
wrote big.jsonl: 200000 lines, 1014400000 bytes (1014 MB)
$ go build -o pin pin.go
$ ./pin -mode sub big.jsonl
mode=sub lines=200000 read=1014 MB kept=3800000 bytes (id-0000000000000000 ... id-0000000000199999)
heap after GC: HeapAlloc=1029.1 MiB HeapInuse=1045.7 MiB NumGC=10
$ ./pin -mode clone big.jsonl
mode=clone lines=200000 read=1014 MB kept=3800000 bytes (id-0000000000000000 ... id-0000000000199999)
heap after GC: HeapAlloc=8.3 MiB HeapInuse=8.7 MiB NumGC=226
$ GODEBUG=gctrace=1 ./pin -mode sub big.jsonl 2>&1 | grep '^gc' | tail -1
gc 10 @0.289s 0%: 0.022+2.0+0.003 ms clock, 0.18+0/3.5/2.4+0.027 ms cpu, 1035->1035->1029 MB, 1595 MB goal, 0 MB stacks, 0 MB globals, 8 P (forced)
$ GODEBUG=gctrace=1 ./pin -mode clone big.jsonl 2>&1 | grep '^gc' | tail -1
gc 226 @0.270s 6%: 0.027+0.58+0.002 ms clock, 0.22+0/0.71/1.1+0.017 ms cpu, 10->10->8 MB, 20 MB goal, 0 MB stacks, 0 MB globals, 8 P (forced)
$ ./pin -mode sub -heapprof heap.pprof big.jsonl
mode=sub lines=200000 read=1014 MB kept=3800000 bytes (id-0000000000000000 ... id-0000000000199999)
heap after GC: HeapAlloc=1029.1 MiB HeapInuse=1045.7 MiB NumGC=10
$ go tool pprof -sample_index=inuse_space -top pin heap.pprof 2>/dev/null | head -8
File: pin
Type: inuse_space
Time: 2026-11-28 00:01:48 KST
Showing nodes accounting for 1026.26MB, 99.90% of 1027.26MB total
Dropped 13 nodes (cum <= 5.14MB)
flat flat% sum% cum cum%
1022.73MB 99.56% 99.56% 1022.73MB 99.56% bufio.(*Scanner).Text (inline)
3.53MB 0.34% 99.90% 1026.26MB 99.90% main.main
$ /usr/bin/time -l ./pin -mode sub big.jsonl 2>&1 | grep -E 'heap after|peak memory footprint'
heap after GC: HeapAlloc=1029.1 MiB HeapInuse=1045.6 MiB NumGC=10
1118700816 peak memory footprint
$ /usr/bin/time -l ./pin -mode clone big.jsonl 2>&1 | grep -E 'heap after|peak memory footprint'
heap after GC: HeapAlloc=8.3 MiB HeapInuse=8.6 MiB NumGC=222
28606968 peak memory footprint
$ rm data.jsonl big.jsonl heap.pprof
참고 자료
- strings.Clone 패키지 문서
- Go 블로그: Go Slices: usage and internals, A possible "gotcha"
- A Guide to the Go Garbage Collector
- bytedance/sonic v1.15.5 README
- Leeway PR #16: Lower first-run memory: read Codex logs line by line