[erlang-questions] node.js vs erlang

Ciprian Dorin Craciun ciprian.craciun@REDACTED
Wed Jun 18 21:37:12 CEST 2014


On Tue, Jun 17, 2014 at 3:41 PM, Joe Armstrong <erlang@REDACTED> wrote:
> It's actually the programming models I want to compare and not the
> performance - what worries me about node is the run-to-completion
> semantics of event callbacks - namely that a long-running event will block
> the server preventing short computations from being performed. The
> short jobs which could be done immediately have to wait until the long jobs
> have finished - this should reflect in the average latencies of a request.
>
> I made a little experiment (a fibonacci server in erlang and node) and fired
> off
> 1000 parallel requests to compute fib(N) with N a random number from 10..40.
>
> As I suspected many of the fib(10) events are blocked by ongoing computation
> of
> fib(40) - this reflect in the latencies.


    I'm not if someone suggested this before, you Joe hinted at it,
but if you need to do a lengthy computational job in pure NodeJS (thus
no background threads / processes / other magic), you could use the
`process.nextTick` and manually implement "reductions" like the BEAM
interpreter does.

      http://nodejs.org/api/process.html#process_process_nexttick_callback


    For example (completely untested code, and probably with "off-by-one bugs"):

~~~~
var fibReductions = 10;

function fib (n, onCompletion) {
    fibRec (2, 1, 1, n, fibReductions, onCompletion);
}

function fibRec (i, s1, s2, n, reductions, onCompletion) {

    if (i >= n) {
        // see notes below why we use `process.nextTick` even here!
        process.nextTick (function () { onCompletion (s2); });
        return;
    }

    if (reductions > 0)
        fibRec (i + 1, s2, s1 + s2, n, reductions - 1, onCompletion);
    else
        process.nextTick (function () {
            fibRec (i + 1, s2, s1 + s2, n, fibReductions, onCompletion);
        });
}
~~~~


    Indeed I cheated by applying the tail-recursive technique to my
function, which eases the implementation of the reduction technique,
else my code would have been more convoluted than this.

    But I hope this proves the point that if needed NodeJS could be
used even in these cases.

    Ciprian.


    P.S.:  I chose to always call `process.nextTick (function () {
callback (outcome); })` even if the result is immediate, because me as
a developer expect that a callback is always called after I exit from
my function, like in the example below:

~~~~
function doSomeStuff () {

    var someClosure = {};

    initiateAction (function (outcome) {
        doSomethingElse (someClosure.expectedValue, outcome);
    });

    someClosure.expectedValue = ...;

    ...
}
~~~~



More information about the erlang-questions mailing list