Search code examples
javascriptperformanceobjectcoordinatesprimitive

Javascript objects vs primitives


I'm currently doing a lot of development in OOP Javascript. In particular, I'm dealing with coordinates and dimensions a lot and I have many variables defined, as objects, like so:

coords = {
    x:10,
    y:15
};

dimensions = {
    width:500,
    height:250
}

But I'm wondering if it would be quicker/more efficient to specify the values as separate, primitive, variables:

coordX = 10;
coordY = 15;

dimWidth = 500;
dimHeight = 240;

Could someone please briefly explain the advantage/disadvantage of each method of string the variables? Usability-wise, I find objects easier, as you can group related values together; although I gather that it is slower. But is it slower, or take up more memory, than defining more variables?

Cheers.

EDIT: Wow! I never expected this many responses, especially so quickly! Thank you all for your responses.

It seems like any performance differences are negatable, but this may only apply to simple scripts. What I have is a constant loop, which needs to run at the highest FPS possible. Each loop uses many object variables for storing data, like above. So is there the potential for performance issues in these circumstances?


Solution

  • Performance should not be an issue - the properties are declared on the object and no prototype chain is necessary to access them (also javascript engines are becoming more and more performant in this area).

    I'd personally prefer to use the OO approach in this situation, since it allows a logical grouping of values, which will be clearer to any other developers who look at your code (and, if you're anything like me, possibly you in a couple of months time!).