diff --git a/common/buf/buffer.go b/common/buf/buffer.go index e0509a17..8259dd9e 100644 --- a/common/buf/buffer.go +++ b/common/buf/buffer.go @@ -199,3 +199,11 @@ func New() *Buffer { v: pool.Get().([]byte), } } + +// StackNew creates a new Buffer object on stack. +// This method is for buffers that is released in the same function. +func StackNew() Buffer { + return Buffer{ + v: pool.Get().([]byte), + } +} diff --git a/proxy/socks/protocol.go b/proxy/socks/protocol.go index cdc98c7c..0d0a8eae 100644 --- a/proxy/socks/protocol.go +++ b/proxy/socks/protocol.go @@ -190,7 +190,7 @@ func (s *ServerSession) Handshake(reader io.Reader, writer io.Writer) (*protocol // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | // +----+------+----------+------+----------+ func ReadUsernamePassword(reader io.Reader) (string, string, error) { - buffer := buf.New() + buffer := buf.StackNew() defer buffer.Release() if _, err := buffer.ReadFullFrom(reader, 2); err != nil { @@ -220,7 +220,7 @@ func ReadUsernamePassword(reader io.Reader) (string, string, error) { // ReadUntilNull reads content from given reader, until a null (0x00) byte. func ReadUntilNull(reader io.Reader) (string, error) { - b := buf.New() + b := buf.StackNew() defer b.Release() for { diff --git a/proxy/socks/protocol_test.go b/proxy/socks/protocol_test.go index 21c24c40..8ad14d33 100644 --- a/proxy/socks/protocol_test.go +++ b/proxy/socks/protocol_test.go @@ -4,6 +4,7 @@ import ( "bytes" "testing" + "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" _ "v2ray.com/core/common/net/testing" @@ -107,3 +108,17 @@ func TestReadUntilNull(t *testing.T) { } } } + +func BenchmarkReadUsernamePassword(b *testing.B) { + input := []byte{0x05, 0x01, 'a', 0x02, 'b', 'c'} + buffer := buf.New() + buffer.Write(input) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + _, _, err := ReadUsernamePassword(buffer) + common.Must(err) + buffer.Clear() + buffer.Extend(int32(len(input))) + } +} diff --git a/proxy/vmess/encoding/client.go b/proxy/vmess/encoding/client.go index a75631a9..6b430a03 100644 --- a/proxy/vmess/encoding/client.go +++ b/proxy/vmess/encoding/client.go @@ -164,7 +164,7 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:]) c.responseReader = crypto.NewCryptionReader(aesStream, reader) - buffer := buf.New() + buffer := buf.StackNew() defer buffer.Release() if _, err := buffer.ReadFullFrom(c.responseReader, 4); err != nil { diff --git a/transport/internet/kcp/io.go b/transport/internet/kcp/io.go index ef14d2ed..5a743186 100644 --- a/transport/internet/kcp/io.go +++ b/transport/internet/kcp/io.go @@ -70,7 +70,7 @@ func (w *KCPPacketWriter) Overhead() int { } func (w *KCPPacketWriter) Write(b []byte) (int, error) { - bb := buf.New() + bb := buf.StackNew() defer bb.Release() if w.Header != nil {