I’m doing a project in javascript, and need to clarify few things. I’ve read that memory management in javascript is not that important since the system does it for us the programmers under the cover, but I’ve also read that sometimes it is good to cache “stuff” for better optimization and so far it is very clear. When we do calculations in a for loop for example
it is better to create a local var and store result in it so we wouldnt have to calculate the same calculation over and over again while going through the loop.
So my question is, I create a json object. Then I want to call it’s property, is it alright to
call it throught the object, like Car.color or to store it in a local var right when I want to access it or something similar. Object = heap, local var = stack as far as I know so does it improve anything or not.
Another example:
var map = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]];
if (r >= 0) {
var num = map[r][k];
if(num === 0)
{
return false;
}
}
Does the num var change anything (for better or worst?), if anyone could expand on this subject that would be nice, Thanks.
Storing a reference to a thing deep in an object really has nothing to do with memory. It has to do with not having to look up the thing over and over again.
Storing the value into a variable is like bookmarking a page on the internet. It is there for you to have for future reference. If you do not bookmark it, you need to figure out how in the world you got there and follow the steps over and over again. Bookmark is fast, having to recreate the steps is slow.
BUT the great news is with the modern day browsers, creating a holding a reference to something does not mean that the code will be faster. In some cases it will be slower! It all depends on the browser, what type of object you are looking up, and what the code is doing.
Most times you should not really care about it unless you are seeing a major performance bottle neck in your application. That is the point you look at the profile tab in your browser and see where the code is taking forever to run.