Skip to content

Commit

Permalink
reduce memory footprint
Browse files Browse the repository at this point in the history
  • Loading branch information
xtaci committed Oct 25, 2016
1 parent 3f1c00c commit 6250093
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 26 deletions.
18 changes: 8 additions & 10 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type Session struct {
dieLock sync.Mutex
chAccepts chan *Stream

xmitPool sync.Pool
dataReady int32 // flag data has arrived
}

Expand All @@ -50,6 +51,10 @@ func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
s.chAccepts = make(chan *Stream, defaultAcceptBacklog)
s.bucket = int32(config.MaxReceiveBuffer)
s.bucketCond = sync.NewCond(&sync.Mutex{})
s.xmitPool.New = func() interface{} {
return make([]byte, (1<<16)+headerSize)
}

if client {
s.nextStreamID = 1
} else {
Expand Down Expand Up @@ -253,23 +258,16 @@ func (s *Session) keepalive() {
// writeFrame writes the frame to the underlying connection
// and returns the number of bytes written if successful
func (s *Session) writeFrame(f Frame) (n int, err error) {
buf := make([]byte, headerSize+len(f.data))
buf := s.xmitPool.Get().([]byte)
buf[0] = f.ver
buf[1] = f.cmd
binary.LittleEndian.PutUint16(buf[2:], uint16(len(f.data)))
binary.LittleEndian.PutUint32(buf[4:], f.sid)
copy(buf[headerSize:], f.data)

s.writeLock.Lock()
n, err = s.conn.Write(buf)
s.writeLock.Unlock()
return n, err
}

// writeBinary writes the byte slice to the underlying connection
func (s *Session) writeBinary(bts []byte) (n int, err error) {
s.writeLock.Lock()
n, err = s.conn.Write(bts)
n, err = s.conn.Write(buf[:headerSize+len(f.data)])
s.writeLock.Unlock()
s.xmitPool.Put(buf)
return n, err
}
19 changes: 3 additions & 16 deletions stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package smux

import (
"bytes"
"encoding/binary"
"sync"
"sync/atomic"

Expand Down Expand Up @@ -71,22 +70,10 @@ func (s *Stream) Write(b []byte) (n int, err error) {
}

frames := s.split(b, cmdPSH, s.id)
// preallocate buffer
buffer := make([]byte, len(frames)*headerSize+len(b))
bts := buffer

// combine frames into a large blob
for k := range frames {
bts[0] = version
bts[1] = frames[k].cmd
binary.LittleEndian.PutUint16(bts[2:], uint16(len(frames[k].data)))
binary.LittleEndian.PutUint32(bts[4:], frames[k].sid)
copy(bts[headerSize:], frames[k].data)
bts = bts[len(frames[k].data)+headerSize:]
}

if _, err = s.sess.writeBinary(buffer); err != nil {
return 0, err
if _, err := s.sess.writeFrame(frames[k]); err != nil {
return 0, err
}
}
return len(b), nil
}
Expand Down

0 comments on commit 6250093

Please sign in to comment.