From 6f423f901fbf125a761bd586446f0d112d77b7c7 Mon Sep 17 00:00:00 2001 From: "PSpeed42@gmail.com" Date: Mon, 18 Apr 2011 05:56:52 +0000 Subject: [PATCH] Reuse one big buffer per thread and copy the outbound smaller buffers. Way faster and way cheaper overall. git-svn-id: http://jmonkeyengine.googlecode.com/svn/trunk@7259 75d07b2b-3a1a-0410-a2c5-0572b91ccdca --- .../com/jme3/network/base/DefaultClient.java | 30 ++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/engine/src/networking/com/jme3/network/base/DefaultClient.java b/engine/src/networking/com/jme3/network/base/DefaultClient.java index 4c515f77f..62333b66f 100644 --- a/engine/src/networking/com/jme3/network/base/DefaultClient.java +++ b/engine/src/networking/com/jme3/network/base/DefaultClient.java @@ -57,6 +57,8 @@ public class DefaultClient implements Client { static Logger log = Logger.getLogger(DefaultClient.class.getName()); + private ThreadLocal dataBuffer = new ThreadLocal(); + private int id = -1; private boolean isRunning = false; private CountDownLatch connecting = new CountDownLatch(1); @@ -197,17 +199,25 @@ public class DefaultClient implements Client if( waitForConnected ) { // Make sure we aren't still connecting waitForConnected(); - } + } + + ByteBuffer buffer = dataBuffer.get(); + if( buffer == null ) { + buffer = ByteBuffer.allocate( 65536 + 2 ); + dataBuffer.set(buffer); + } + buffer.clear(); + + // Convert the message to bytes + buffer = MessageProtocol.messageToBuffer(message, buffer); + + // Since we share the buffer between invocations, we will need to + // copy this message's part out of it. This is because we actually + // do the send on a background thread. + byte[] temp = new byte[buffer.remaining()]; + System.arraycopy(buffer.array(), buffer.position(), temp, 0, buffer.remaining()); + buffer = ByteBuffer.wrap(temp); - // For now just send direclty. We allocate our - // own buffer each time because this method might - // be called from multiple threads. If writing - // is queued into its own thread then that could - // be shared. - // Writing is now done on a background thread. - // If we ever share a ByteBuffer then it will need to be - // copied before handing off. - ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); if( message.isReliable() || fast == null ) { if( reliable == null ) throw new RuntimeException( "No reliable connector configured" ); -- 2.11.0