I'm using typed arrays in a Javascript game to send data between the client (running in a browser) and the server (running node.js). I can send messages back and forth no problem but I'm interested in reusing my typed arrays rather than creating a new one each time I send a message.
Here's my sendMessage code:
function sendMessage(socket, data) {
// data is JSON
var encoded = BISON.encode(data);
if (socket.isBinary) {
var len = encoded.length,
bytes = new Uint32Array(len);
for (var i = 0; i < len; ++i) {
bytes[i] = encoded.charCodeAt(i);
}
}
if (server && socket.isBinary) {
socket.send(bytes, { binary: true, mask: false });
} else {
socket.send(encoded);
}
}
and here's my readMessage code:
function readMessage(data) {
if (data instanceof ArrayBuffer) {
var bytes = new Uint32Array(data);
data = String.fromCharCode.apply(null, bytes);
}
var message = JSON.stringify(BISON.decode(data));
return JSON.parse(message);
}
Each time I send a message I create a new Uint32Array, initializing it to the length of the message I intend to send. Rather than create a new array each time I'd like reuse this array for each message.
My current line of thought on this is to determine my maxMessageSize and initialize the array with this length. maxMessageSize would be the largest allowed message that one could send over the socket.
Most messages are not likely to be exactly maxMessageSize in size. In these cases would I need to pad the length of the message with some value (null?). When reading the value on the other end of the socket how would I know when this padding began?
In writing all of this out another question has occurred to me: is this even worth the effort?
As far as I know there is no way to change the length of a Uint*Array once it has been constructed, you can only get sub arrays from them.
Any padding would have to be done with 32-bit integers, if you tried to use null, ToInt(null) is 0 so you'd have a 0 in that entry. If you wanted to pad like this, you'd need to pass some length value (either first or last entry in array), which you'd need to look at on the received end to know when to trim the data and would mean maxMessageSize is one less.
Using a subarray might be what you want though, construct your max-length array, fill it up, then use .subarray(0, len) to get the actual array you want. I'm not sure if this has any advantages over constructing a new one each time.