Search code examples
javascriptperformancevariablesjavascript-objectsmemory-efficient

Should I use multiple variables or a single object in Javascript?


If I want to store multiple values related to each other, should I use multiple variables or a single object? Which one would be more efficient?
Note: These variables are defined inside an IIFE, so they are not globals.

Example:

// Option 1
let value1 = "Value 1";
let value2 = 2;
let value3 = true;

// Option 2
let value = {
    "1": "Value 1",
    "2": 2,
    "3": true
};

// Which one is more efficient?

Solution

  • EDIT: OP actually put these variables inside an immediately invoked function and a function is already an object, therefore just keep them there.

    Original answer:

    In short, Objects.

    Are you defining your variables as globals? Global variables clutter up the global namespace and are slower to look up than local variables.

    Since you used let, there is no variable hoisting and your variables have block scope, tending to be much tidier. Any context of execution different than Array and global (except local blocks) is actually an Object. So depending on the context of execution, in a tidy context of execution like a function, a closure, an instance of a "class" (ES6, or functions used as classes), you would already have your desired tidyness. Functions and classes, extending Object are therefore Objects, inheriting Object.prototype.

    Object.prototype is useful when handling data, for instance Object.assign() is useful for shallow coying and merging.

    You can easily access the Array.prototype by using Object.keys() and Object.values() , allowing many operations such as map, filter, reduce. Here is an example:

    Object.filter = (obj, predicate) => Object.keys(obj)
        .filter( key => predicate(obj[key]))
        .reduce( (res, key) => (res[key] = obj[key], res), {} );
    

    So generally speaking Object is a better idea resulting in wider possibilities. Of course you could create Objects when you need them as well.

    To sum up your 3 choices are Array, Object (including functions, classes, (nevermind blocks)) or Global. Globals are to be avoided, Objects may dominate Arrays.