init: v1.0.0

This commit is contained in:
yaole
2026-05-27 23:03:00 +08:00
commit 8d97f750eb
466 changed files with 80067 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
/*
pool is pool of tmp obj
临时对象的存储,每次GC都可能会回收。
*/
package objectpool
import (
"math/big"
"sync"
)
// BytePool is pool for []byte
var BytePool = sync.Pool{
New: func() interface{} {
b := make([]byte, 0, 1024)
return &b
},
}
var SmallBytePool = sync.Pool{
New: func() interface{} {
b := make([]byte, 0, 256)
return &b
},
}
var LargeBytePool = sync.Pool{
New: func() interface{} {
b := make([]byte, 0, 4096)
return &b
},
}
// GetBytes wraps the pool, for clear data
func GetBytes() []byte {
b := BytePool.Get().(*[]byte)
return (*b)[:0]
}
func PutBytes(b []byte) {
BytePool.Put(&b)
}
func GetSmallBytes() []byte {
b := SmallBytePool.Get().(*[]byte)
return (*b)[:0]
}
func PutSmallBytes(b []byte) {
BytePool.Put(&b)
}
func GetLargeBytes() []byte {
b := LargeBytePool.Get().(*[]byte)
return (*b)[:0]
}
func PutLargeBytes(b []byte) {
BytePool.Put(&b)
}
// BigIntPool is pool for Big.Int
var BigIntPool = sync.Pool{
New: func() interface{} {
b := new(big.Int)
return b
},
}
func GetBigInt() *big.Int {
b := BigIntPool.Get().(*big.Int)
b.SetInt64(0)
return b
}
func PutBigInt(b *big.Int) {
BigIntPool.Put(b)
}
+107
View File
@@ -0,0 +1,107 @@
package objectpool
import (
"fmt"
"math/big"
"sync"
"testing"
"time"
)
func TestBigIntPool(t *testing.T) {
var wg sync.WaitGroup
a := time.Now().UnixNano()
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
for i := 0; i < 1000000; i++ {
a := new(big.Int)
a.SetInt64(1)
a.Add(a, a)
}
wg.Done()
}()
}
wg.Wait()
b := time.Now().UnixNano()
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
for j := 0; j < 1000000; j++ {
a := GetBigInt()
a.SetInt64(1)
a.Add(a, a)
PutBigInt(a)
}
wg.Done()
}()
}
wg.Wait()
c := time.Now().UnixNano()
fmt.Println("without pool ", b-a)
fmt.Println("with pool ", c-b)
}
func bytesFactory(n int) []byte {
return make([]byte, n)
}
func doSomeWork(b []byte) {
for i := 0; i < len(b); i++ {
b[i] = byte(i)
}
}
func TestBytesFactory(t *testing.T){
a := 0
fmt.Printf("%p\n",&a)
b := bytesFactory(1024) // b is not on stack
fmt.Printf("%p\n", &(b[0]))
}
func TestBytesPool(t *testing.T) {
var wg sync.WaitGroup
a := time.Now().UnixNano()
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
for i := 0; i < 10000; i++ {
a := bytesFactory(1024)
doSomeWork(a)
}
wg.Done()
}()
}
wg.Wait()
b := time.Now().UnixNano()
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
for j := 0; j < 10000; j++ {
a := GetBytes()
doSomeWork(a)
PutBytes(a)
}
wg.Done()
}()
}
wg.Wait()
c := time.Now().UnixNano()
fmt.Println("without pool ", b-a)
fmt.Println("with pool ", c-b)
}
func BenchmarkBytesPool(b *testing.B) {
for j := 0; j < 10000; j++ {
a := GetBytes()
doSomeWork(a)
PutBytes(a)
}
}
func BenchmarkBytesMake(b *testing.B) {
for j := 0; j < 10000; j++ {
a := bytesFactory(1024)
doSomeWork(a)
}
}