优化内存缓存相关代码

This commit is contained in:
GoEdgeLab
2023-10-09 12:48:30 +08:00
parent 87270479d3
commit e85f221953
2 changed files with 14 additions and 12 deletions

View File

@@ -126,9 +126,7 @@ func (this *MemoryFragmentPool) Get(expectSize int64) (resultBytes []byte, ok bo
return return
} }
if expectSize < minMemoryFragmentPoolItemSize { // DO NOT check min segment size
return
}
this.mu.RLock() this.mu.RLock()

View File

@@ -32,23 +32,20 @@ func NewMemoryWriter(memoryStorage *MemoryStorage, key string, expiredAt int64,
ModifiedAt: fasttime.Now().Unix(), ModifiedAt: fasttime.Now().Unix(),
Status: status, Status: status,
} }
if expectedBodySize > 0 { if expectedBodySize > 0 && expectedBodySize <= maxMemoryFragmentPoolItemSize {
bodyBytes, ok := SharedFragmentMemoryPool.Get(expectedBodySize) // try to reuse memory bodyBytes, ok := SharedFragmentMemoryPool.Get(expectedBodySize) // try to reuse memory
if ok { if ok {
valueItem.BodyValue = bodyBytes valueItem.BodyValue = bodyBytes
valueItem.IsPrepared = true
} else { } else {
if isDirty { if expectedBodySize <= (16 << 20) {
if expectedBodySize >= minMemoryFragmentPoolItemSize {
SharedFragmentMemoryPool.IncreaseNew()
}
var allocSize = (expectedBodySize/16384 + 1) * 16384 var allocSize = (expectedBodySize/16384 + 1) * 16384
valueItem.BodyValue = make([]byte, allocSize)[:expectedBodySize] valueItem.BodyValue = make([]byte, allocSize)[:expectedBodySize]
} else {
valueItem.BodyValue = make([]byte, expectedBodySize)
}
}
valueItem.IsPrepared = true valueItem.IsPrepared = true
SharedFragmentMemoryPool.IncreaseNew()
}
}
} }
var w = &MemoryWriter{ var w = &MemoryWriter{
storage: memoryStorage, storage: memoryStorage,
@@ -170,6 +167,13 @@ func (this *MemoryWriter) Discard() error {
this.storage.locker.Lock() this.storage.locker.Lock()
delete(this.storage.valuesMap, this.hash) delete(this.storage.valuesMap, this.hash)
if this.item != nil &&
!this.item.isReferring &&
cap(this.item.BodyValue) >= minMemoryFragmentPoolItemSize {
SharedFragmentMemoryPool.Put(this.item.BodyValue)
}
this.storage.locker.Unlock() this.storage.locker.Unlock()
return nil return nil
} }