Njs: for loop performance concerns

Created on 28 Mar 2020  路  2Comments  路  Source: nginx/njs

A small synthetic test.

for (var i = 0; i < 1e9; i++) {
}

Node.js v13.11.0: 440ms
njs@e6d5690: 17008ms

Just wondering, why such a difference?

CentOS 8 Linux 4.18.0-80.el8.x86_64, 4GB RAM, Intel Core [email protected]

answered performance question

Most helpful comment

@vryabinin

Just wondering, why such a difference?

node.js uses V8 which compiles JS code into the native x86.
njs is an interpreter (like CPython implementation of python).

See for the reference https://bellard.org/quickjs/bench.html

The conclusions are:

  1. njs is not the the best for heavy-weight math and CPU intensive operations.
  2. njs works the best as a glue code for nginx.
  3. njs+nginx does not plan to replace node.js, njs is used to extend the functionality of nginx.
  4. njs is better to compare with openresty ecosystem but with JS instead of lua.
  5. you would see such performance difference (x10-x20) mostly for such synthetic tests. In real cases the difference is much lower.

All 2 comments

@vryabinin

Just wondering, why such a difference?

node.js uses V8 which compiles JS code into the native x86.
njs is an interpreter (like CPython implementation of python).

See for the reference https://bellard.org/quickjs/bench.html

The conclusions are:

  1. njs is not the the best for heavy-weight math and CPU intensive operations.
  2. njs works the best as a glue code for nginx.
  3. njs+nginx does not plan to replace node.js, njs is used to extend the functionality of nginx.
  4. njs is better to compare with openresty ecosystem but with JS instead of lua.
  5. you would see such performance difference (x10-x20) mostly for such synthetic tests. In real cases the difference is much lower.

@vryabinin

Also, constant expressions are not optimized, it's better to avoid them in a loop.

$ cat y.js
console.time(1);
for (var i = 0; i < 1e9; i++) {
}
console.timeEnd(1);

console.time(2);
for (var i = 0; i < 10**9; i++) {
}
console.timeEnd(2);

$ njs y.js 
1: 13975.273739ms
2: 66203.931495ms

$ node y.js 
1: 855.346ms
2: 863.493ms
Was this page helpful?
0 / 5 - 0 ratings

Related issues

drsm picture drsm  路  3Comments

drsm picture drsm  路  4Comments

an0ma1ia picture an0ma1ia  路  4Comments

xeioex picture xeioex  路  3Comments

porunov picture porunov  路  4Comments