mJS heap usage optimisation guidance

Scripting, necessarily, occupies scarce heap resources. We are writing an application in mJS which is likely to grow as requirements change (they always do) and hence we want to be sure that we are architecting it, from the outset, to optimise heap usage, saving for the future :-).

Is there any written guidance anywhere on how to construct an mJS application such that it minimise heap usage?

Thinking along the lines of:

  • separation of code into different .JS files and how this influences heap usage,
  • impact of ffi() calls under different circumstances (exactly when do they start occupying heap?),
  • impact of comments in code on heap usage,
  • how long can a function realistically be,
  • what prevents garbage collection,
  • when do variables go out of scope (and, conversely, how can they be kept in scope),
  • etc.

So that’s a “no” then…?

There is no such guidance.
For strings, there is an significant optimisations: strings of 5 characters or less take significantly less resourses, so keep variable names short.
Comments have no impact, other that taking filesystem space.
Separating code into different .js files also have no impact.
Generally, have small functions, as little vars as possible.
Split complex expressions - since parsing is recursive descent, thus takes C stack space.

1 Like

OK, thanks. I don’t think I have a single variable name that is less than 5 characters, will take a look at that.

We are trying to optimize ram in our mjs application and have some questions regarding what’s more ram efficient.
1.

let var1 = 1;
let var2 = 2;
let var3 = 3;
let var4 = 4;
let var5 = 5;

//VS

let vars = {
    var1: 1,
    var2: 2,
    var3: 3,
    var4: 4,
    var5: 5,
};
  1. Creating a new variable vs assigning a variable to a new type.

     let calculate = function (nbr1, nbr2) {
         let result = nbr1 + nbr2;
         let resultAsStr = JSON.stringify(result);
         print(resultAsStr);
     };
     // VS
     let calculate = function (nbr1, nbr2) {
         let result = nbr1 + nbr2;
         result = JSON.stringify(result);
         print(result);
     };
    

Many small functions vs few large functions?
4.
let SENSOR_SERVER_PROPERTY_ID_LIGHT = 0x004E;
VS
let SENSOR_SERVER_PROPERTY_ID_LIGHT = 78; // 0x004E

Thank you

Each JS entity takes space . So if you create an extra variable or function - that’s an extra space.
Thus,

  1. let a=1, b=2, c=3; is more efficient than let vars = {a:1,b:2,c:3}; BUT: the former litters the global namespace. MJS keeps object attributes in a linked list, thus attribute lookup is O(N). Therefore for larger applications the latter is better.
  2. The latter. But you can just avoid making a variable. print(JSON.stringify(a+b))
  3. Fewer larger functions, less intermediate variables, short names
  4. let PROPS = {LIGHT: 0x4e, ...}; .... func(PROPS.LIGHT, ...)