Javascript performance: Variable vs Large object's attribute - javascript

I am building a number of HTML5 games and I am not sure about one thing in javascript.
When dealing with a large object (with a lot of attributes and methods), is it somehow different, if I store the attribute value in a variable?
Say I have to check for some value in application.data.setings.foo.bar multiple times per second. Should I store it in a variable fooBar? If I understand it correctly, the variable would be just a reference, so it shouldn't matter.
so: Should you store values of large objects' attributes in variables?

This diagram give you your answer. http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html#access_times_for_object_properties_by_de

I believe what you are asking is:
If you have a variable called:
application.data.settings.foo.bar = { some: 'value' }
Is it more performant to access it by using application.data.settings.foo.bar - or to instead say: var bar = application.data.settings.foo.bar and then refer to bar.
My guess is that the assignment to variable is probably slightly more performant - simply because there are less steps for the interpreter to take in order to access the relevant item. If you use application.data.settings.foo.bar - the interpreter has to utilize the reference to the application object, then reference it's data property, then reference its setting property, then reference its foo property, then reference its bar property. This is 5 steps.
If you reference it into a local variable for access - you are still hitting the same object, but you are hitting it directly on each reference.
At the end of the day, however, this is unlikely to be a performance enhancement which is hugely noticeable, unless you are doing a lot of heavy, rapid-access looping or something similar.

For numbers you may see a performance improvement if you place it in a variable

Related

variable assignment vs passing directly to a function

What are the advantages/disadvantages in terms of memory management of the following?
Assigning to a variable then passing it to a function
const a = {foo: 'bar'}; // won't be reused anywhere else, for readability
myFunc(a);
Passing directly to a function
myFunc({foo: 'bar'});
The first and second code have absolutely no difference between them (unless you also need to use a later in your code) in the way the variable is passed.
The are only 2 cases in which the first might be preferred over the second.
You need to use the variable elsewhere
The variable declaration is too long and you want to split it in two lines or you are using a complex algorithm and want to give a name to each step for readability.
It depends on the implementation of the JavaScript engine. One engine might allocate memory for the variable in the first example and not allocate memory in the directly-passed example, while another implementation might be smart enough to compile the code in such a way that it makes the first example not allocate memory for a variable and thus leaves the first example behaving as the directly-passed example.
I don't know enough about the specific engines to tell you what each one does specifically. You'd have to take a look at each JS engine (or ask authors of each) to get a more conclusive answer.

Understanding Object Chaining

I am learning about object/method chaining in JavaScript and I would like make sure I understand it correctly.
If the following code is an example of JavaScript without object chaining:
var people = helper.getPeople();
var bob = people.find("bob");
var email = bob.getEmail();
and the code below is after applying object chaining:
var email = helper.getPeople().find("bob").getEmail();
Am I to consider object chaining as simply a way to "drill down" into an object, reaching "sub-objects" or properties/methods etc...?
If these two examples of code are supposed to do the same thing, why is a var declaration not required in the object-chained example? I do not understand how the chained statement is the same if no new variables are declared in the process.
I can see the value of saving space and writing the code on one line, and all my research online has shown that this is considered an intuitive, simplified way to write. However, I feel that I am able to read the first example (without object chaining) better. That may just be because I am new to JavaScript, but which example would be considered good coding practice?
Additionally, is the purpose of object chaining merely to reach objects that are not defined in the global scope? A way of reaching local objects?
Thank you for your help!
Am I to consider object chaining as simply a way to "drill down" into an object, reaching "sub-objects" or properties/methods etc...? Is the purpose of object chaining merely to reach objects that are not defined in the global scope? A way of reaching local objects?
It could be. Every of these methods does return another object with methods, that's the secret of chaining. "Drilling down" might be an appropriate wording for some uses, like the one you've shown, where different objects are returned.
However, whether these returned objects are hidden, local "sub-objects", accessible through other means or just created on the fly by that method, or even the original object that returns itself, is dependent on the methods and API design. All options make valid chaining, though.
If these two examples of code are supposed to do the same thing, why is a var declaration not required in the object-chained example? I do not understand how the chained statement is the same if no new variables are declared in the process.
Returning objects that are immediately accessed does not require them to be assigned to any variable. They of course are held in memory somewhere, but don't have an explicit identifier attached to them.
That may just be because I am new to JavaScript, but which example would be considered good coding practice?
Depends. Usually, a good practise is not to create variables if you don't need them. If you are only interested in the email and won't access all the people and bob again, there's no reason to create variables for them.
The readability can be increased by putting each method call on a new line, which is common in JS for chaining:
var email = helper.getPeople()
.find("bob")
.getEmail();
(with various styles of indentation for the subsequent lines)

extracting all used javascript variables

I have a big object defined in the global scope called global. I would like to dynamically find all the referenced properties under my variable global. That is, all the properties that were accessed during the execution of the code.
I want to do static code analysis to extract all the referenced properties under my variable. I can search for these patterns: global.PROPERTY_NAME AND global[PROPERTY_NAM]. However, what about the complicated cases like these ones
var tmp="PROPERTY_NAME";
global[tmp]
OR
var tmp=global;
tmp.PROPERTY_NAME
and the other ones?
I don't want to get all the variable's properties. I only want a list of the referenced ONES!! the properties that were referenced in my source code only
After your edit:
What you're looking for is JavaScript Proxy objects. Here is a tutorial on how to do this using them.
Proxy objects let you wrap an object and execute a method whenever its properties are accessed. Unfortunately as it currently stands they are not widely supported.
This is currently only way in JavaScript to accomplish this without changing your original global object.
You can turn them on in Chrome by enabling experimental JavaScript in the about:flags tab.
Before your edit:
The feature you're looking for is called reflection, JavaScript supports it well and natively
Here is some code that iterates through an object and gets its properties
for(var prop in global){
if(global.hasOwnProperty(prop)){ //this is to only get its properties and not its prototype's
alert(prop+" => "+global[prop]);
}
}
This is fairly cross-browser. More modern browsers allow you to do this in simpler ways like Object.keys(global) which returns an array containing all its enumerable properties, or Object.getOwnPropertyNames(global) which returns both enumerable and not-enumerable properties.
Due to the dynamic nature of JavaScript you won't achieve that with static code analysis. Think about cases like this:
var prop = document.getElementById('prop').value;
global[prop];
Impossible. The alternative, dynamic analysis, would mean that you modify your global object to log access to its properties, then run the code. This is easily possible in JavaScript but it won't help you either because how would you assure that you have covered every possible access? Especially in a 5 MB JavaScript, there are most likely edge cases that you will oversee.
So, if you can't narrow down your requirement, it won't be possible.

JavaScript Global Object referencing vs 'this'

I'm working on an application framework written as an object literal and for the sake of simplicity I'd like to do two things:
Have the object available globally
Use the object name (as globally defined) for all references (vs. using this)
So, I've run some tests, done research, and am not finding any good reason NOT to take this approach. My question is - am I missing something? Perf tests actually seem to favor my method and from a logistical level I don't see any issues. Looking at other frameworks I've seen a mix, but I know that the this reference is revered by many programmers.
For reference...
A very minimal example of my approach:
var myobj = {
someVal: 'foo',
init: function(){
// Make myobj available globally
window.myobj = myobj;
// Fire off a method
myobj.doStuff();
},
doStuff: function(){
// Just print out the contents...
console.log(myobj.someVal);
}
}
myobj.init();
Note the references are all to the global, not this.
Like I said, I've seen a mix of this, I guess I just would like to know if this could cause issues in the long-run or if this a much ado about nothing.
As far as limitations go, the first thing that comes to mind is that you could only have one instance of this object. Trying to initialize a new one would wipe out the object.
Another reason for using this rather than a global variable name is that this will point to the correct object even if the name of the variable changes.
If you really want this to be a "create once" global object whose name never changes then this technique isn't technically wrong. But it won't be able to be used in any other situation. It is probably wiser to consider writing code that will be more adaptable if the requirements change (for instance if you use a library that causes a naming conflict with the chosen variable name)
Using this lets you be flexible in renaming the variable and passing it in different contexts without worrying about tracking variable names. It also will make it easy to change if naming conflicts arise.

Javascript variable reuse?

Is it OK to reuse variables for different data types in terms of performance and memory usage ?
What happens to old data, is it garbage collected immediately after type casting ?
It's OK to reuse variables, although unless you're doing some crazy things (say so in the question) with the amount of variables you're using, you probably should not reuse them too liberally in this way. It's considered good coding practice in general to have a variable declared to point to a specific thing, and use a different variable when you want to refer to something else.
"Variables" in Javascript are just references. They're not inherently expensive-- they don't take up more space than their text in the code and a few bytes in memory pointing to somewhere else. If you reuse a variable name by setting the reference to something else (or null/undefined), then the GC will know that that original reference is detached and know that it can be collected.
The GC in whatever browser or environment you're using will choose when to actually run the collector based on lots of factors.
Full disclosure: I have no knowledge of the internals of any particular JavaScript engines. I'm going from general principles of VMs and interpreters.
Usually, variable names just refer to other memory locations. So, whether you remove an old variable (which happens when it goes out of scope) and introduce a new one, or replace the current contents with a new object, doesn't matter much in terms of memory allocation.
Garbage collection might be different in each implementation. Immediate garbage collection is difficult; the only way I can think of doing it involves reference counters, and it's tough to make that work even for cyclic data structures. So, most garbage collectors in the wild do non-immediate collection cycles where, each time, a whole bunch of data gets removed. The cycles might, for example, be run automatically when memory use goes above a certain threshold within the engine (but it'll usually be more refined than that).
JavaScript is a loosely-typed language, and can store any datatype in any variable (even reused ones).
If you are combining types, though, you should check them periodically using the typeof keyword to ensure they are the type you think they are (for instance, trying to perform a mathematical operation on a string will concatenate or break, depending on the situation).
Furthermore, JavaScript variables stick around as long as they are within scope. Once a scope is left, the variables within it are destroyed (eventually - it's automatic and transparent). As far as garbage collection on reassigned variables, the old value is destroyed as soon as the new value is assigned.

Categories