Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go Optimizations 101 #216

Open
ivanburak opened this issue Feb 7, 2022 · 2 comments
Open

Go Optimizations 101 #216

ivanburak opened this issue Feb 7, 2022 · 2 comments

Comments

@ivanburak
Copy link

3.9 Use value cache pool to avoid some allocations

You write:

Personally, I find the design of sync.Pool seldom satisfies the needs in practice. So I often use
custom value cache pool implementations in my Go projects.

Could you give some examples of your custom value cache pool?

@go101
Copy link
Owner

go101 commented Feb 10, 2022

The example above the quoted text shows how to use the custom value cache pool.
It is very simple, but it does show the whole mechanism.

import "container/list"

var npcPool = struct {
	sync.Mutex
	*list.List
}{
	List: list.New(),
}

func newNPC() *NPC {
	npcPool.Lock()
	defer npcPool.Unlock()
	if npcPool.Len() == 0 {
		return &NPC{}
	}
	return npcPool.Remove(npcPool.Front()).(*NPC)
}

func releaseNPC(npc *NPC) {
	npcPool.Lock()
	defer npcPool.Unlock()
	*npc = NPC{} // zero the released NPC
	npcPool.PushBack(npc)
}

@go101
Copy link
Owner

go101 commented Feb 10, 2022

I will add a generic version when Go 1.18 is released.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants