Deep-clone messages when there are multiple recipients

Fixes #85

As well as adding deep-clone (via the new dependency on the 'clone' module), we no longer clone the message if there is a single recipient. This makes simple node-to-node flows more efficient.

I've done some simple profiling using process.hrtime to time how long the Node.send function takes, and at best, this change is neutral to performance.
pull/75/merge
Nicholas O'Leary 2013-11-21 14:03:17 +00:00
parent 6a4aa1ff21
commit e1dbb95396
2 changed files with 23 additions and 14 deletions

View File

@ -25,6 +25,7 @@
"mqtt": "~0.3.3", "mqtt": "~0.3.3",
"ws": "~0.4.31", "ws": "~0.4.31",
"fs-extra": "~0.8.1", "fs-extra": "~0.8.1",
"clone": "~0.1.11",
"mustache": "~0.7.2", "mustache": "~0.7.2",
"cron":"1.x", "cron":"1.x",
"ntwitter":"0.5.0", "ntwitter":"0.5.0",

View File

@ -17,6 +17,7 @@ var util = require("util");
var EventEmitter = require("events").EventEmitter; var EventEmitter = require("events").EventEmitter;
var fs = require("fs"); var fs = require("fs");
var path = require("path"); var path = require("path");
var clone = require("clone");
var events = require("./events"); var events = require("./events");
var storage = null; var storage = null;
@ -149,22 +150,28 @@ Node.prototype.send = function(msg) {
for (var i in this.wires) { for (var i in this.wires) {
var wires = this.wires[i]; var wires = this.wires[i];
if (i < msg.length) { if (i < msg.length) {
for (var j in wires) {
if (msg[i] != null) { if (msg[i] != null) {
var msgs = msg[i]; var msgs = msg[i];
if (!util.isArray(msg[i])) { if (!util.isArray(msg[i])) {
msgs = [msg[i]]; msgs = [msg[i]];
} }
if (wires.length == 1) {
// Single recipient, don't need to clone the message
var node = registry.get(wires[0]);
if (node) {
for (var k in msgs) { for (var k in msgs) {
var mm = msgs[k]; var mm = msgs[k];
var m = {}; node.receive(mm);
for (var p in mm) {
if (mm.hasOwnProperty(p)) {
m[p] = mm[p];
} }
} }
} else {
// Multiple recipients, must send message copies
for (var j in wires) {
var node = registry.get(wires[j]); var node = registry.get(wires[j]);
if (node) { if (node) {
for (var k in msgs) {
var mm = msgs[k];
var m = clone(mm);
node.receive(m); node.receive(m);
} }
} }
@ -172,6 +179,7 @@ Node.prototype.send = function(msg) {
} }
} }
} }
}
} }
module.exports.Node = Node; module.exports.Node = Node;