@@ -130,10 +130,16 @@ type FixedArray struct {
130130
1311314 . ** Memory Management**
132132
133- - The library uses internal 4K buffers for efficient unpacking
133+ - When packing, the library pre-allocates a buffer with the exact size needed for the data
134+
135+ ``` go
136+ bufferSize := packer.Sizeof (value, options)
137+ buffer := make ([]byte , bufferSize)
138+ ```
139+
140+ - For unpacking, the library uses internal 4K buffers for efficient operations
134141 - When unpacking, slice/string fields in your struct will directly reference these internal buffers
135142 - These buffers will remain in memory as long as your struct fields reference them
136- - Example of memory retention:
137143
138144 ` ` ` go
139145 type Message struct {
@@ -143,12 +149,31 @@ type FixedArray struct {
143149 func processRetain() {
144150 messages := make([]*Message, 0)
145151
152+ // >> Important:
153+ // The Field struct is just a metadata description object
154+ // Its lifecycle end does not affect user struct fields that have been set via unsafe operations
155+ // Because unsafe operations have directly modified the underlying pointer of user struct fields to point to the 4K buffer
156+ // >> Therefore:
157+ // Releasing the Field struct will not cause the slice references on the 4K buffer to disappear
158+ // These references only disappear when the user structs using these slices are GC'ed
159+ // The 4K buffer's lifecycle depends on the lifecycle of all user structs referencing it
160+
146161 // Each unpacked message's Data field references the internal buffer
147162 for i := 0; i < 10; i++ {
148163 msg := &Message{}
164+ // During unpacking:
165+ // 1. unpackBasicTypeSlicePool provides 4K buffer
166+ // 2. Field struct handles metadata
167+ // 3. unsafe operations point msg.Data to part of 4K buffer
149168 struc.Unpack(reader, msg)
169+ // Even if Field struct is released now
170+ // msg.Data still points to 4K buffer
171+ // Only when msg is GC'ed will this reference disappear
150172 messages = append(messages, msg)
151- // The internal buffer can't be GC'ed because msg.Data references it
173+ // Internal buffer can't be GC'ed because msg.Data references it
174+ // Field struct's lifecycle is irrelevant to 4K buffer references
175+ // 4K buffer references are held by user structs
176+ // Only when all user structs referencing this 4K buffer are GC'ed can the buffer be collected
152177 }
153178 }
154179 ` ` `
0 commit comments