Reclaiming memory from Nodes

An interesting view. from that Q:

It's always pass by value, but for objects the value of the variable is a reference

Most things in JS are objects and this explains it much better than I did but is saying much the same.

The author means that by passing a reference, you're passing a reference value (another way to think of it is passing the value of the memory address

OK, so some semantics there and I kind of get it but I'm not convinced that it matters at least most of the time, the effect is pretty much the same.

This is the reason Node-RED works at all of course - the so-called msg is just an object variable and so is (mostly) passed by reference (reference value) from node-to-node. Only where you have 2 or more wires off an output do you get a copy. If this weren't the case, node-red would be a nightmare and would rapidly bloat itself into oblivion.

OK, now I'm a little confused. Perhaps you could share a bit more of your code where you doing this so that we can see the diff in the code?

In my nodes, I implement a function called nodeInstance

// ... module-level setup ...
module.exports = function( RED ) {
    // ... module-level code ...
    function nodeInstance(config) {
        // ... instance-level code ...
        // - fn defined here so that it inherits `RED`. I don't know of another way to do this.

        // Create the node
        RED.nodes.createNode(this, config)
        ...
        // Take a reference to `this` in case the context changes
        const node = this
        ...
        // apply the properties from the config to the node (this)
        node.name            = config.name  || ''
        node.topic           = config.topic || ''
        node.url             = config.url   || 'uibuilder'
        ...
        // define the handler function for incoming messages
        // - defined here so it inherits both `RED` and `node`, I don't know a better way to do that
        function nodeInputHandler(msg, send, done) { ... }
        // Register a handler for incoming messages
        node.on('input', nodeInputHandler)
        // Register the handler for node-red closing or the instance being (re)deployed
        node.on('close', function(removed, done) { ... }
    }

    // register the node
    RED.nodes.registerType(moduleName, nodeInstance, { ... })
    ...
    // ... Express API code ...
}
//EOF

You seem to be suggesting that const node = this has a real memory impact? I can't say I've seen this myself and I use the same approach in other places as well such as in the oneditprepare function in the node's html file.

I'm certainly not an expert JavaScript programmer by any stretch though so I may have this all wrong. I would certainly be interested if there is a better/cleaner way to do things.

1 Like