소스 검색

Use ReadFull instead of ioutil.ReadAll to read objects (#76)

* Use ReadFull instead of ioutil.ReadAll to read objects

ioutil.ReadAll uses a bytes.Buffer, which allocates memory by doubling.
Since we know exactly how muh data we expect to get, we can allocate it
in advance. This reduces the total amount of allocation, and ensures
that the slice stored in the item won't have excess capacity (which can
affect memory usage if the item is held for a long time, for instance in
a secondary cache).
Andrew Rodland 7 년 전
부모
커밋
f867c99a8d
1개의 변경된 파일4개의 추가작업 그리고 2개의 파일을 삭제
  1. 4 2
      memcache/memcache.go

+ 4 - 2
memcache/memcache.go

@@ -23,7 +23,6 @@ import (
 	"errors"
 	"fmt"
 	"io"
-	"io/ioutil"
 	"net"
 
 	"strconv"
@@ -481,11 +480,14 @@ func parseGetResponse(r *bufio.Reader, cb func(*Item)) error {
 		if err != nil {
 			return err
 		}
-		it.Value, err = ioutil.ReadAll(io.LimitReader(r, int64(size)+2))
+		it.Value = make([]byte, size+2)
+		_, err = io.ReadFull(r, it.Value)
 		if err != nil {
+			it.Value = nil
 			return err
 		}
 		if !bytes.HasSuffix(it.Value, crlf) {
+			it.Value = nil
 			return fmt.Errorf("memcache: corrupt get result read")
 		}
 		it.Value = it.Value[:size]