From e1dbb95396e1865198231e4090806fc0692c034b Mon Sep 17 00:00:00 2001 From: Nicholas O'Leary Date: Thu, 21 Nov 2013 14:03:17 +0000 Subject: [PATCH] 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. --- package.json | 1 + red/nodes.js | 36 ++++++++++++++++++++++-------------- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index 00e2cf4d6..619d3808a 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "mqtt": "~0.3.3", "ws": "~0.4.31", "fs-extra": "~0.8.1", + "clone": "~0.1.11", "mustache": "~0.7.2", "cron":"1.x", "ntwitter":"0.5.0", diff --git a/red/nodes.js b/red/nodes.js index 42463bc2e..f4e3df7d4 100644 --- a/red/nodes.js +++ b/red/nodes.js @@ -17,6 +17,7 @@ var util = require("util"); var EventEmitter = require("events").EventEmitter; var fs = require("fs"); var path = require("path"); +var clone = require("clone"); var events = require("./events"); var storage = null; @@ -149,23 +150,30 @@ Node.prototype.send = function(msg) { for (var i in this.wires) { var wires = this.wires[i]; if (i < msg.length) { - for (var j in wires) { - if (msg[i] != null) { - var msgs = msg[i]; - if (!util.isArray(msg[i])) { - msgs = [msg[i]]; - } - for (var k in msgs) { - var mm = msgs[k]; - var m = {}; - for (var p in mm) { - if (mm.hasOwnProperty(p)) { - m[p] = mm[p]; - } + if (msg[i] != null) { + var msgs = msg[i]; + if (!util.isArray(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) { + var mm = msgs[k]; + node.receive(mm); } + } + } else { + // Multiple recipients, must send message copies + for (var j in wires) { var node = registry.get(wires[j]); if (node) { - node.receive(m); + for (var k in msgs) { + var mm = msgs[k]; + var m = clone(mm); + node.receive(m); + } } } }