github.com/dgraph-io/ristretto@v0.1.2-0.20240116140435-c67e07994f91/contrib/demo/node.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  
     7  	"github.com/dgraph-io/ristretto/z"
     8  	"github.com/dustin/go-humanize"
     9  )
    10  
    11  type node struct {
    12  	val  int
    13  	next *node
    14  }
    15  
    16  var alloc *z.Allocator
    17  
    18  func printNode(n *node) {
    19  	if n == nil {
    20  		return
    21  	}
    22  	if n.val%100000 == 0 {
    23  		fmt.Printf("node: %d\n", n.val)
    24  	}
    25  	printNode(n.next)
    26  }
    27  
    28  func main() {
    29  	N := 2000001
    30  	root := newNode(-1)
    31  	n := root
    32  	for i := 0; i < N; i++ {
    33  		nn := newNode(i)
    34  		n.next = nn
    35  		n = nn
    36  	}
    37  	fmt.Printf("Allocated memory: %s Objects: %d\n",
    38  		humanize.IBytes(uint64(z.NumAllocBytes())), N)
    39  
    40  	runtime.GC()
    41  	printNode(root)
    42  	fmt.Println("printing done")
    43  
    44  	if alloc != nil {
    45  		alloc.Release()
    46  	} else {
    47  		n = root
    48  		for n != nil {
    49  			left := n
    50  			n = n.next
    51  			freeNode(left)
    52  		}
    53  	}
    54  	fmt.Printf("After freeing. Allocated memory: %d\n", z.NumAllocBytes())
    55  
    56  	var ms runtime.MemStats
    57  	runtime.ReadMemStats(&ms)
    58  	fmt.Printf("HeapAlloc: %s\n", humanize.IBytes(ms.HeapAlloc))
    59  }