Permalink
Browse files

net: batch socket string writes

  • Loading branch information...
1 parent 5631549 commit 79ce70920c8fd27bd4db95975782f766bee989ca @bnoordhuis committed Oct 29, 2011
Showing with 65 additions and 3 deletions.
  1. +65 −3 lib/net.js
View
@@ -364,6 +364,64 @@ Socket.prototype.__defineGetter__('remotePort', function() {
});
+var corkedConnection = null;
+
+
+function cork(conn, string, encoding, cb) {
+ if (corkedConnection === null) {
+ process.nextTick(uncork);
+ corkedConnection = conn;
+ conn.corkedString = string;
+ conn.corkedEncoding = encoding;
+ } else if (corkedConnection !== conn || conn.corkedEncoding !== encoding) {
+ uncork();
+ corkedConnection = conn;
+ conn.corkedString = string;
+ conn.corkedEncoding = encoding;
+ } else {
+ conn.corkedString += string;
+ }
+
+ if (cb) {
+ if (conn.corkedCallbacks) {
+ conn.corkedCallbacks.push(cb);
+ } else {
+ conn.corkedCallbacks = [cb];
+ }
+ }
+}
+
+
+function uncork() {
+ var conn = corkedConnection;
+ if (conn === null || conn._handle === null) return;
+ corkedConnection = null;
+
+ var data = new Buffer(conn.corkedString, conn.corkedEncoding);
+
+ var callbacks = conn.corkedCallbacks;
+ delete conn.corkedString;
+ delete conn.corkedEncoding;
+ delete conn.corkedCallbacks;
+
+ var cb = undefined;
+ if (callbacks && callbacks.length) {
+ if (callbacks.length === 1) {
+ cb = callbacks[0];
+ } else {
+ cb = runCallbacks.bind(callbacks);
+ }
+ }
+
+ conn.write(data, cb);
+}
+
+
+function runCallbacks() {
+ for (var i = 0, n = this.length; i < n; ++i) this[i]();
+}
+
+
/*
* Arguments data, [encoding], [cb]
*/
@@ -382,9 +440,13 @@ Socket.prototype.write = function(data, arg1, arg2) {
}
}
- // Change strings to buffers. SLOW
- if (typeof data == 'string') {
- data = new Buffer(data, encoding);
+ if (typeof data === 'string') {
+ cork(this, data, encoding, cb);
+ return false;
+ } else if (corkedConnection) {
+ // Have corked string data but caller now tries to write a buffer.
+ // Flush string data first.
+ uncork();
}
this.bytesWritten += data.length;

0 comments on commit 79ce709

Please sign in to comment.