Which is the fastest way of accessing JavaScript object? - javascript

I want to know what is the best way of accessing a JavaScript object, dot operator or []:
data.property or data["property"]?

Both are more or less the same, except in Safari in which case dot notation is significantly faster.
You're much better off concentrating on DOM manipulation, DOM size, and CSS complexity as major sources of performance problems in Javascript applications.
That said, if you are doing a lot of property access in a loop, a local variable will be much faster than either property access or array lookup. Copy an object property into a variable if it is going to be accessed repeatedly. Do not use the "with" statement, incidentally. It can slow down local variable access by introducing another object into the scope chain.
Variables defined in local scope will be accessed far more quickly than those in global, as the Javascript engine first looks through all of the variables locally, then checks all of the variables in global scope. Scopes can nest as well, so the farther up the nesting chain the variable resides the longer it will take to find. That's why it's best to cache something like "document" in a local variable if it is going to be accessed more than once.

Both are the same speed. Also, if you are concerned with the level of speed in accessing a field attached to a reference, I think you might be going down the wrong path to tuning your code.

I would venture to guess that data.property is ever-so-slightly faster, but it may be difficult to measure. Indeed, JSPerf shows no distinction

The best way of accessing object properties has generally nothing to do with speed. Dot operator is used for syntactic sugar (I.E. this.hasElements() is easier to read, write and process in your brain than this["hasElements"]()) whenever possible and the brackets are used when the key name is a variable or has illegal characters.

Related

Is it a good idea to mutate Node's global object?

Is it a good idea to add properties to Node's global object? Searches for this lead me to a discussion of global variables in Node, and frankly I can't find much about the global object for some reason.
From my understanding, global in Node is analogous to the window object that's used in the conventional JS environment, and mutating that is generally frowned upon.
I ask because I'm using Electron whose docs list all sorts of examples that use global, and they even provide an API that lets us set/get global properties from other processes.
From a recent code review, my team was asked to replace the use of global with our own Node module so to avoid overwriting important global attributes set by Node/Electron/3rd party resources.
This seems like a good idea, but why then does Electron recommend the use of global? Why is that the paradigm?
Taking a closer look at the examples, it looks like they recommend only adding one property to the global (sharedObject), so this isn't as bad as I thought, but is this good enough, or should I really take the time to create a separate Node module?
Perhaps this is an opinion-based question.

Is there any reason for "saving" variables?

I've got this function a colleague once has written:
setSentence: function (e) {
this.setState({
issueText: e.target.value
});
if (this.refs.messages.textContent.length > 0 && e.target.value.length > 2) {
this.refs.messages.textContent = '';
}
},
He uses e.target.value on two places within the code. I would tend to make something like this:
let textBoxContent = e.target.value;
Then use the variable with the more descriptive name instead.
I once talked to him about these avoiding variables-thing. He just said that he wants "to save variables".
Would like to change these code-pieces but I'm still not sure ...
So therefore my question:
Does "saving variables" respectively avoiding variables in the code make any sense?
There is no economy in "saving variables" while repeating verbose code over and over. To me, this definitely falls in the category of DRY (Don't Repeat Yourself).
Javascript interpreters are very optimized for fast access to local variables. When a variable is being referenced, the very first scope that is looked in is the local scope so it will be found immediately and because of that and because there is no outside access to local variables, code within the function using them can be optimized pretty well.
In the end, it's probably as much a personal coding preference as anything.
My personal rule is that if I have some multi-step reference such as e.target.value and I'm using it more than once in a function, then I will creating a meaningfully named local variable and assign it to that so I can then just use the local variable in the multiple places and avoid repeating the same multi-step property reference over and over (a textbook example of DRY).
This definitely makes the code easier to read too, both because you have a meaningful variable name and because it's just a simple variable rather than a multi-step property reference that has a generic name. While, it might technically be one additional line of code for the local variable assignment, it saves a lot of repeated property lookups so the theory is that it should be faster to save the end value into textBoxContent and not have to have the interpreter lookup e.target.value every time.
Also, you should never fall for people who want to micro-optimize regular code as they first write it. Optimizations like this generally only need apply to 0.000001% of all your code and only after you've proven exactly where your bottleneck for performance is. And, even then you will have to devise multiple benchmarks in your target environment to prove what actually makes things faster (not use one person opinion - measurements only).
Before that, all your code should first be correct, clear, readable, maintainable, extensible, DRY, appropriate performance and about 10 other priorities before anyone thinks about a micro-optimization. If you apply the above priorities to the case you asked about, you will always decide to assign e.target.value to a local variable if you are referencing it more than once within a context.

JavaScript- properties and variables

In my code I was to deleting custom-objects. I realized, we can not delete objects which are declared using 'var'. (after reading this documentation Delete operator).
Most of my objects are declared and initialized using 'var'. They can't be deleted in single delete statement(unless I loop through it and delete each property.)
I can set them to 'null'.
My custom objects are relatively bigger in size (may block considerable chunk of memory.
For better memory management and performance should I use 'properties' or 'variables' to store my objects? Will it make a difference?
Please provide any references for better insight on 'properties' and 'variables' in javascript.
globalProp = {//can be deleted, it is a 'property' to global object.
'name': 'Mia',
'age': 34,
'sex': 'F'
};
var globalVar = {//can not be deleted with delete statement, it is variable of global object
'name': 'Lia',
'age': 25,
'sex': 'F'
};
(In above code, we can refer to globalProp as 'window.globalProp' but can't refer to globalVar as window.globalVar.)
Have fiddle
JavaScript has runtime and garbage collector with some complex cleaning and managing algorithms, any try to interfere or speed them will proably do the opposite, resulting some runtime penalty. it is the best to leave the memory managment to the underlying runtime.
however, there are some points that you might want to consider:
1) avoid global variables as much as possible. this is a good advice for any language that support global/static variables. global variables means global references with no scope - the referenced object will live on as long as the (global) reference holds it. this danger increases even more if the global variable is an array or object which keeps on appending children to itself.
this is the common case which leads to a memory leak in managed languages
2) avoid cyclic references - don't make one member variable point to a different object, and that object holds a member which points to the first object. this will make a hard time for the garbage collector.
3) write clean, simple, maintainable code. this may seems as unrelated preach, but an easier, short, maintainable code will probably enhance the interperter/compiler ability to optimize the code.
4) don't assume nothing about how the code affects the speed. there are so many layers down there that you can't simply assume anything. benchmark the code to get real facts.
5) don't optimize unless you need to (you probably don't).
so for your question : declare anything with var as much as possible. declaring a variable with var will make them local - when the function ends the reference will get out of scope and the GC can start determine the destruction time for the object earlier. declaring your object without var will make them global - it is unclear when will the GC decide to delete the object, thus slowing things down.
and as you know - declaring variables global can lead to many bugs, keep things scoped. don't use delete. it's just wrong.

Javascript optimization...global variables

I am making a webapp. I have a fairly basic question about javascript performance. Sometimes I need a global variable to store information that is used the entire time the website is open.
An example is a variable called needs_saved. It is true or false to say whether the page needs saved. I might have another variable called is_ie, ie_version, or space_remaining.
These are all variable that I need in various functions throughout the app.
Now, I know global variables are bad because they require the browser to search each level of function scope. But, I don't know if there is any better way to store values that are needed throughout the program.
I know I could create a global object called 'program_status' and give it the properties is_ie, ie_version, etc... But is this any better since it would first have to find my program_status object (stored as a global variable), and then the internal property?
Maybe I'm overthinking this.
Thanks
You have nothing to worry about.
The performance impact of a global variable is minute.
Global variables are discouraged because they can make code harder to maintain.
In your case, they won't.
The reason global variable use should be kept to a minimum is because the global namespace gets polluted when there's a lot of them, and there's a good chance of a clash if your program needs to use some 3rd party libraries which also create their own globals.
Creating a single object to hold all of your global state is a good idea since it limits the number of identifiers you need to reserve at the global level.
To solve performance problems, you can then create a local reference to that object in any scope where you need to access it multiple times:
So instead of
if (globalState.isIe) { alert(globalState.ieMessage); }
you can do
var state = globalState;
if (state.isIe) { alert(state.ieMessage); }
You don't need to do this if you only access the state object once. In any case, even if you never do this, the performance penalties will be negligible.
If you're worried about performance, code something clean then run a profiler on it to optimize. I know both Safari and Google Chrome have one, and it's pretty sure Firebugs includes one for Firefox too. Heck, even Internet Explorer 8 has one.

Why is it bad to make elements global variables in Javascript?

I've heard that it's not a good idea to make elements global in JavaScript. I don't understand why. Is it something IE can't handle?
For example:
div = getElementById('topbar');
I don't think that's an implementation issue, but more a good vs bad practice issue. Usually global * is bad practice and should be avoided (global variables and so on) since you never really know how the scope of the project will evolve and how your file will be included.
I'm not a big JS freak so I won't be able to give you the specifics on exactly why JS events are bad but Christian Heilmann talks about JS best practices here, you could take a look. Also try googling "JS best practices"
Edit: Wikipedia about global variables, that could also apply to your problem :
[global variables] are usually
considered bad practice precisely
because of their nonlocality: a global
variable can potentially be modified
from anywhere, (unless they reside in
protected memory) and any part of the
program may depend on it. A global
variable therefore has an unlimited
potential for creating mutual
dependencies, and adding mutual
dependencies increases complexity. See
Action at a distance. However, in a
few cases, global variables can be
suitable for use. For example, they
can be used to avoid having to pass
frequently-used variables continuously
throughout several functions.
via http://en.wikipedia.org/wiki/Global_variable
Is it something IE can't handle?
No it is not an IE thing. You can never assume that your code will be the only script used in the document. So it is important that you make sure your code does not have global function or variable names that other scripts can override.
Refer to Play Well With Others for examples.
I assume by "events" you mean the event-handling JavaScript (functions).
In general, it's bad to use more than one global variable in JS. (It's impossible not to use at least one if you're storing any data for future use.) That's because it runs into the same problem as all namespacing tries to solve - what if you wrote a method doSomething() and someone else wrote a method called doSomething()?
The best way to get around this is to make a global variable that is an object to hold all of your data and functions. For example:
var MyStuff = {};
MyStuff.counter = 0;
MyStuff.eventHandler = function() { ... };
MyStuff.doSomething = function() { ... };
// Later, when you want to call doSomething()...
MyStuff.doSomething();
This way, you're minimally polluting the global namespace; you only need worry that someone else uses your global variable.
Of course, none of this is a problem if your code will never play with anyone else's... but this sort of thinking will bite you in the ass later if you ever do end up using someone else's code. As long as everyone plays nice in terms of JS global names, all code can get along.
There shouldn't be any problem using global variables in your code as long as you are wrapping them inside a uniqe namespase/object (to avoid collision with scripts that are not yours)
the main adventage of using global variable in javascript derives from the fact that javascript is not a strong type language. there for, if you pass somes complex objects as arguments to a function, you will probebly lose all the intellisence for those objects (inside the function scope.)
while using global objects insteads, will preserve that intellisence.
I personally find that very usfull and it certainly have place in my code.
(of course, one should alwayse make the right balance between locales and globals variables)

Categories

Resources