Has anybody done any work in this regard?
I am doing some code review, and could not help but notice that there is a glaring inefficiency that should be solvable easily, but doesn't seem to be.
Basically, in web sockets we have to do something like
sock.write(new ByteString([0]));
sock.write(new ByteString(payload, "us-ascii"));
sock.write(new ByteString([255]));
in C, I would write this either a writev() with three arrays of char in an iovec, or maybe something like
int writeIt(fd, payload, payloadLen)
{
static char *buf = NULL;
static size_t bufLen = 0;
if (bufLen - 2 > payloadLen)
{
buf = realloc(buf, PAGESIZE + ((payloadLen + 2) * (payloadLen + 2) / PAGESIZE));
buf[0] = (char)0;
}
buf[payloadLen + 1] = (char)0xff;
memcpy(buf + 1, payload, payloadLen);
return write(fd, buf, payloadLen + 2);
}
(obviously this is untested code that relies on a blocking write, but it's the memory management that's interesting, not the I/O for now)
So -- any ideas for a "good" way to fix this?
The first one that pops up is to implement a sockets API that essentially implements writev(), but that still means that I will be churning a ByteArray per write, in order to knock the string down to 8-bit rep'n. That also breaks compatibility with Node.js's net module, which I am trying to keep.
The next one that pops up is to essentially implement the C solution above, only using ByteArray.copy() instead of memcpy. I'm still creating a temporary ByteArray to this for each write, though.
Should we perhaps be looking at a new copy + conversion form for ByteArray instances? Code like this might be more ideal from a memory/GC POV:
function writeIt(payload, payloadLen)
{
if (!writeIt.buf || writeIt.buf.length < payloadLen + 2)
{
writeIt.buf = new (require("binary").ByteArray)(PAGESIZE + ((payloadLen + 2) * (payloadLen + 2) / PAGESIZE));
writeIt.buf[0] = 0;
}
writeIt.buf[payloadLen - 1] = 255;
writeIt.buf.copy(1, payloadLen, payload, "us-ascii");
}
Thoughts from the list? Does anybody know what Node.js, python, perl, etc do under the hood?
Wes
--
Wesley W. Garland
Director, Product Development
PageMail, Inc.
+1 613 542 2787 x 102