1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

Pre-allocate memory to reduce the number of allocations (#272)

This commit is contained in:
Yurun
2024-11-27 14:58:02 +08:00
committed by GitHub
parent 1eb793420e
commit 05b85a2131
12 changed files with 15 additions and 12 deletions

View File

@@ -209,7 +209,7 @@ func (dl *DoublyLink[T]) Size() int {
// Values return slice of all doubly linklist node value
func (dl *DoublyLink[T]) Values() []T {
result := []T{}
result := make([]T, 0, dl.length)
current := dl.Head
for current != nil {
result = append(result, current.Value)

View File

@@ -212,7 +212,7 @@ func (sl *SinglyLink[T]) Size() int {
// Values return slice of all singly linklist node value
func (sl *SinglyLink[T]) Values() []T {
result := []T{}
result := make([]T, 0, sl.length)
current := sl.Head
for current != nil {
result = append(result, current.Value)

View File

@@ -31,7 +31,7 @@ func NewArrayQueue[T any](capacity int) *ArrayQueue[T] {
// Data return slice of queue data
func (q *ArrayQueue[T]) Data() []T {
items := []T{}
items := make([]T, 0, q.tail-q.head)
for i := q.head; i < q.tail; i++ {
items = append(items, q.data[i])
}

View File

@@ -27,7 +27,7 @@ func NewLinkedQueue[T any]() *LinkedQueue[T] {
// Data return slice of queue data
func (q *LinkedQueue[T]) Data() []T {
res := []T{}
res := make([]T, 0, q.length)
current := q.head
for current != nil {

View File

@@ -24,7 +24,7 @@ func NewLinkedStack[T any]() *LinkedStack[T] {
// Data return stack data
func (s *LinkedStack[T]) Data() []T {
res := []T{}
res := make([]T, 0, s.length)
current := s.top
for current != nil {

View File

@@ -147,7 +147,7 @@ func printTreeNodes[T any](nodes []*datastructure.TreeNode[T], level, maxLevel i
printSpaces(firstSpaces)
newNodes := []*datastructure.TreeNode[T]{}
newNodes := make([]*datastructure.TreeNode[T], 0, len(nodes)*2)
for _, node := range nodes {
if node != nil {
fmt.Printf("%v", node.Value)