github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/runtime/allocator.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package runtime
    18  
    19  import (
    20  	"sync"
    21  )
    22  
    23  // AllocatorPool simply stores Allocator objects to avoid additional memory allocations
    24  // by caching created but unused items for later reuse, relieving pressure on the garbage collector.
    25  //
    26  // Usage:
    27  //
    28  //	memoryAllocator := runtime.AllocatorPool.Get().(*runtime.Allocator)
    29  //	defer runtime.AllocatorPool.Put(memoryAllocator)
    30  //
    31  // A note for future:
    32  //
    33  //	consider introducing multiple pools for storing buffers of different sizes
    34  //	perhaps this could allow us to be more efficient.
    35  var AllocatorPool = sync.Pool{
    36  	New: func() interface{} {
    37  		return &Allocator{}
    38  	},
    39  }
    40  
    41  // Allocator knows how to allocate memory
    42  // It exists to make the cost of object serialization cheaper.
    43  // In some cases, it allows for allocating memory only once and then reusing it.
    44  // This approach puts less load on GC and leads to less fragmented memory in general.
    45  type Allocator struct {
    46  	buf []byte
    47  }
    48  
    49  var _ MemoryAllocator = &Allocator{}
    50  
    51  // Allocate reserves memory for n bytes only if the underlying array doesn't have enough capacity
    52  // otherwise it returns previously allocated block of memory.
    53  //
    54  // Note that the returned array is not zeroed, it is the caller's
    55  // responsibility to clean the memory if needed.
    56  func (a *Allocator) Allocate(n uint64) []byte {
    57  	if uint64(cap(a.buf)) >= n {
    58  		a.buf = a.buf[:n]
    59  		return a.buf
    60  	}
    61  	// grow the buffer
    62  	size := uint64(2*cap(a.buf)) + n
    63  	a.buf = make([]byte, size)
    64  	a.buf = a.buf[:n]
    65  	return a.buf
    66  }
    67  
    68  // SimpleAllocator a wrapper around make([]byte)
    69  // conforms to the MemoryAllocator interface
    70  type SimpleAllocator struct{}
    71  
    72  var _ MemoryAllocator = &SimpleAllocator{}
    73  
    74  func (sa *SimpleAllocator) Allocate(n uint64) []byte {
    75  	return make([]byte, n)
    76  }