Skip to content

Instantly share code, notes, and snippets.

@avneesh91
Created November 30, 2023 17:30
Show Gist options
  • Save avneesh91/f41bd60ea1337c139be33a7bcd58c9ed to your computer and use it in GitHub Desktop.
Save avneesh91/f41bd60ea1337c139be33a7bcd58c9ed to your computer and use it in GitHub Desktop.

Revisions

  1. avneesh91 created this gist Nov 30, 2023.
    43 changes: 43 additions & 0 deletions pool.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    package main

    import (
    "sync"
    "testing"
    )

    type MyStruct struct {
    FirstName string
    LastName string
    }

    func myObjectPool() *sync.Pool {
    return &sync.Pool{
    New: func() interface{} {
    return &MyStruct{}
    },
    }
    }

    func withoutPool() {
    obj := &MyStruct{}
    _ = obj
    }

    func withPool(pool *sync.Pool) {
    obj := pool.Get().(*MyStruct)
    _ = obj
    pool.Put(obj)
    }

    func BenchmarkWithoutPool(b *testing.B) {
    for i := 0; i < b.N; i++ {
    withoutPool()
    }
    }

    func BenchmarkWithPool(b *testing.B) {
    pool := myObjectPool()
    for i := 0; i < b.N; i++ {
    withPool(pool)
    }
    }