this is just a simple performance question, helping me understand the javascript engine.
for this I’m was wondering, what is faster: declaring multiple variables for certain values or using one object containing multiple values.
example:
var x = 15;
var y = 300;
vs.
var sizes = { x: 15, y: 300 };
this is just a very simple example, could of course differ in a real project.
does this even matter?
A complete answer for that question would be really long. So I’ll try to explain a few things only. First, maybe most important fact, even if you declare a variable with
var, it depends where you do that. In a global scope, you implicitly would also write that variable in an object, most browsers call itwindow. So for instanceIf we do the same thing within the context of a function things change. Within the context of a function, we would write that variable name into its such called ‘Activation Object’. That is, an internal object which the js engine handles for you. All formal parameters, function declarations and variables are stored there.
Now to answer your actual question: Within the context of a function, its always the fastest possible access to have variables declared with
var. This again is not necesarrily true if we are in the global context. The global object is very huge and its not really fast to access anything within.If we store things within an object, its still very fast, but not as fast as variables declared by
var. Especially the access times do increase. But nonetheless, we are talking about micro and nanoseconds here (in modern browser implementations). Old’ish browsers, especially IE6+7 have huge performance penalties when accessing object properties.If you are really interested in stuff like this, I highyl recommend the book ‘High Performance Javascript‘ by Nicholas C. Zakas. He measured lots of different techniques to access and store data in ECMAscript for you.
Again, performance differences for object lookups and variables declared by
varis almost not measureable in modern browsers. Old’ish Browsers like FF3 or IE6 do show a fundamental slow performance for object lookups/access.