Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive are JS function calls (compared to allocating memory for a variable)?

Given some JS code like that one here:

  for (var i = 0; i < document.getElementsByName('scale_select').length; i++) {
    document.getElementsByName('scale_select')[i].onclick = vSetScale;
  }

Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that?

I am not sure how large the effect is in real life, with the result from getElementsByName typically having < 10 items. I'd like to understand the underlying mechanics anyway.

Also, if there's anything else noteworthy about the two options, please tell me.

like image 627
Hanno Fietz Avatar asked Sep 22 '08 13:09

Hanno Fietz


People also ask

Does JavaScript allocate memory automatically?

In order to not bother the programmer with allocations, JavaScript will automatically allocate memory when values are initially declared. Some function calls result in object allocation. Some methods allocate new values or objects:

How do you allocate memory in a function?

Some function calls result in object allocation. Some methods allocate new values or objects: Using values basically means reading and writing in allocated memory. This can be done by reading or writing the value of a variable or an object property or even passing an argument to a function.

How much do function calls affect performance?

This can cause a big hit for performance. In a nutshell: function calls may or may not impact performance. The only way to tell is to profile your code. Don't try to guess where the slow code spots are, because the compiler and hardware have some incredible tricks up their sleeves.

How does memory management work in JavaScript?

Low-level languages like C, have manual memory management primitives such as malloc () and free (). In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore ( garbage collection ).


2 Answers

Definitely. The memory required to store that would only be a pointer to a DOM object and that's significantly less painful than doing a DOM search each time you need to use something!

Idealish code:

var scale_select = document.getElementsByName('scale_select');
for (var i = 0; i < scale_select.length; i++)
    scale_select[i].onclick = vSetScale;
like image 102
Oli Avatar answered Oct 11 '22 04:10

Oli


Caching the property lookup might help some, but caching the length of the array before starting the loop has proven to be faster.

So declaring a variable in the loop that holds the value of the scale_select.length would speed up the entire loop some.

var scale_select = document.getElementsByName('scale_select');
for (var i = 0, al=scale_select.length; i < al; i++)
    scale_select[i].onclick = vSetScale;
like image 24
ScottKoon Avatar answered Oct 11 '22 04:10

ScottKoon