pool.go 705 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package bytepool
  2. import "sync"
  3. var (
  4. bufPool5k sync.Pool
  5. bufPool2k sync.Pool
  6. bufPool1k sync.Pool
  7. bufPool sync.Pool
  8. )
  9. func Get(size int) []byte {
  10. var x interface{}
  11. if size >= 5*1024 {
  12. x = bufPool5k.Get()
  13. } else if size >= 2*1024 {
  14. x = bufPool2k.Get()
  15. } else if size >= 1*1024 {
  16. x = bufPool1k.Get()
  17. } else {
  18. x = bufPool.Get()
  19. }
  20. if x == nil {
  21. return make([]byte, size)
  22. }
  23. buf := x.([]byte)
  24. if cap(buf) < size {
  25. return make([]byte, size)
  26. }
  27. return buf[:size]
  28. }
  29. func Put(buf []byte) {
  30. size := cap(buf)
  31. if size >= 5*1024 {
  32. bufPool5k.Put(buf)
  33. } else if size >= 2*1024 {
  34. bufPool2k.Put(buf)
  35. } else if size >= 1*1024 {
  36. bufPool1k.Put(buf)
  37. } else {
  38. bufPool.Put(buf)
  39. }
  40. }