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

confusing for mem malloc #11

Closed
wongoo opened this issue Aug 17, 2021 · 2 comments
Closed

confusing for mem malloc #11

wongoo opened this issue Aug 17, 2021 · 2 comments

Comments

@wongoo
Copy link

wongoo commented Aug 17, 2021

func (mp *MemPool) Malloc(size int) []byte {
	pbuf := mp.pool.Get().(*[]byte)
	if cap(*pbuf) < size {
		if cap(*pbuf)+holderSize >= size {
			*pbuf = (*pbuf)[:cap(*pbuf)]
			*pbuf = append(*pbuf, holderBuffer[:size-len(*pbuf)]...) // <--- allocation occur when exceed cap, why not just create a new buffer ?  
		} else {
			mp.pool.Put(pbuf)
			newBuf := make([]byte, size)
			pbuf = &newBuf
		}
	}

	if mp.Debug {
		mp.saveAllocStack(*pbuf)
	}

	return (*pbuf)[:size]
}
@lesismal
Copy link
Owner

lesismal commented Aug 17, 2021

Thank you for you feedback!

allocation occur when exceed cap, why not just create a new buffer ?

  1. If we just create a new buffer, we should reput the old into the pool, then there will be more buffers in the pool. And lots of the small buffer will be hardly reused and cause more reput and create.
  2. Most of the time, append would not trigger the realloc(buffer move and copy), even if trigger the realloc, the buffer should be returned to the runtime or system, we don't need worry about it.
  3. try this test: https://github.com/lesismal/nbio/blob/master/mempool/mempool_test.go#L7.
    And change the code to that just creates a new buffer every time when the cap is not enough, compare the differences with the current implementation.

@lesismal
Copy link
Owner

望哥,内存池这里的实现还有疑问或者建议没?如果没有,咱关了呀 😄

@wongoo wongoo closed this as completed Aug 25, 2021
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