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.
Are there any performance issues with passing an argument as an expression, instead of first making it a variable?
someFunction( x+2 );
vs.
var total = x+2;
someFunction( total );
And how about functions?
someFunction( someOtherFunction() );
No. And, more important, this sort of micro-optimization is (almost certainly) meaningless.
Having said that, if you were to use the result of the expression more than once, then there might be some completely imperceptible and totally not-worth-worrying-about benefit to saving the result of the calculation.
Write it to be readable. Don't worry about this stuff.
Just the obvious: Making a variable creates a variable. This costs memory and consumes some time when executing. Afterwards, it either will need time to garbage collect it, or not free the memory if your function leaks.
However, you won't notice any differences. The performance is not measurable at that level. Rule of thumb: Use variables when you really need them or when they improve readabilty of your code.
Though the difference is minimal, the answer is really implementation-specific; JavaScript engines almost certainly differ in how they allocate things. However, I can tell you that most likely, the differences are similar to what they would be in most other languages of which I can examine the memory and processor registers in the debugger. Let's examine one scenario:
var sum = x+2;
someFunction(sum);
This allocates memory to hold sum, which hangs around as long as the function is in scope. If the function ends up being a closure, this could be forever. In a recursive function this could be significant.
someFunction(x+2);
In most languages, this will compute x+2 on the stack and pass the result to someFunction. No memory is left hanging around.
The answer would be exactly the same for a function return value.
So in summary:
The exact answer depends on the JavaScript engine's implementation.
Most likely you won't notice a performance difference.
You may want to use variables when the result is re-used, or, when you want to examine the result easily in the debugger.
It's mostly a matter of personal preference.
Creating a local variable whose scope does not extend beyond the current function does not incur any cost compared to not creating one and writing the expression directly as the argument to the function. In fact, nothing tells you that writing someFunction(x*2) won't be transformed to code that binds a variable to the result of x*2 internally by the javascript compiler - indeed, many compilers and JITs use SSA as one of their intermediate representations, in which form a variable is always bound to the result of every sub expression. See the relevant Wikipedia entry. Whether in a closure or not makes no difference.
The only two relevant questions that should concern you to make a choice between introducing a new variable and writing the expression as an argument directly are:
Readability: does naming the result of the expression make clearer what the expression is computing;
Cost of evaluating the expression: if you will be writing the expression more than once, then binding a variable to the result will you to reuse avoid recomputing the result everytime. This is only relevant if your expression is expected to take a long time to compute.
If you only need to write the expression once inside a function definition then binding a variable to the result may well make the result live in memory longer than is strictly necessary, but this is nearly always completely irrelevant: most function calls are very short lived, in many cases the result does not take up much memory and the memory allocated on the stack will be reclaimed upon function exit and the memory allocated on the heap will be reclaimed by garbage collector soon thereafter.
This question already has an answer here:
javascript object access performance
(1 answer)
Closed 8 years ago.
I'm writing an animation loop and so trying to optimize for speed. This involves sacrificing a lot of readablity, but I'm wondering if at some point it becomes counter-productive. For example, I might start with something like this:
var Animation = Animations[Current_Animation];
var Sequence = Animation.Sequences[Current_Sequence];
var Action = Sequence.Actions[Current_Action];
if (Action.Repeat_Count != Action.Repeat_End) Sequence.Index--;
But when I remove the extraneous variables for optimization, it comes out with truly massive references:
if (Animations[Current_Animation].Sequences[Current_Sequence].Actions
[Animations[Current_Animation].Sequences[Current_Sequence].Index].Repeat_Count
!= Animations[Current_Animation].Sequences[Current_Sequence].Actions
[Animations[Current_Animation].Sequences[Current_Sequence].Index].Repeat_End)
Animations[Current_Animation].Sequences[Current_Sequence].Index--;
My loop is now full of such monstrosities. So I'm wondering if the interpreter having to stop and sort all of that out might actually be slower than using the placeholders. Or does it automagically know what it all means without using any extra CPU?
Thanks!
Your shorter code is more readable and faster on any JS engine I've used, not to mention if this is client side JS the download time will be shorter for less having less bytes!
However you should be using the var keyword so that all your variables aren't in the global scope. I'm sure that you have no reason for Animation, Sequence, and Action to be globals in the above code, since they are really just meant to be temporary variables, but since they are not explicitly declared as local to the current function scope, they are automatically global.
var Animation = Animations[Current_Animation];
var Sequence = Animation.Sequences[Current_Sequence];
var Action = Sequence.Actions[Current_Action];
if (Action.Repeat_Count != Action.Repeat_End) Sequence.Index--;
Per a talk given at SXSW (slide 40) this week, it is not impacting on performance in any significant way in practically any widely deployed browser.
The version which uses references (the first code sample), however, is MUCH easier to read, IMO. As noted by PaulP.R.O. it would need proper scope control via var, but it is (admittedly subjectively) better code.
As I have learnt, its better to cache the values in objects which we need repeatedly. For example, doing
var currentObj = myobject.myinnerobj.innermostobj[i]
and using 'currentObj' for further operations is better for performance than just
myobject.myinnerobj.innermostobj[i]
everywhere, like say in loops.. I am told it saves the script from looking-up inside the objects every time..
I have around 1000 lines of code, the only change I did to it with the intention of improving performance is this (at many locations) and the total time taken to execute it increased from 190ms to 230ms. Both times were checked using firebug 1.7 on Firefox 4.
Is what I learnt true (meaning either I am overusing it or mis-implemented it)? Or are there any other aspects to it that I am unaware of..?
There is an initial cost for creating the variable, so you have to use the variable a few times (depending on the complexity of the lookup, and many other things) before you see any performance gain.
Also, how Javascript is executed has changed quite a bit in only a few years. Nowadays most browsers compile the code in some form, which changes what's performant and what's not. It's likely that the perforance gain from caching reference is less now than when the advice was written.
The example you have given appears to simply be Javascript, not jQuery. Since you are using direct object property references and array indices to existing Javascript objects, there is no lookup involved. So in your case, adding var currentObj... could potentially increase overhead by the small amount needed to instantiate currentObj. Though this is likely very minor, and not uncommon for convenience and readability in code, in a long loop, you could possibly see the difference when timing it.
The caching you are probably thinking of has to do with jQuery objects, e.g.
var currentObj = $('some_selector');
Running a jQuery selector involves a significant amount of processing because it must look through the entire DOM (or some subset of it) to resolve the selector. So doing this, versus running the selector each time you refer to something, can indeed save a lot of overhead. But that's not what you're doing in your example.
See this fiddle:
http://jsfiddle.net/SGqGu/7/
In firefox and chrome (didn't test IE) -- the time is identical in pretty much any scenario.
Is what I learnt true (meaning either
I am overusing it or mis-implemented
it)? Or are there any other aspects to
it that I am unaware of..?
It's not obvious if either is the case because you didn't post a link to your code.
I think most of your confusion comes from the fact that JavaScript developers are mainly concerned with caching DOM objects. DOM object lookups are substantially more expensive than looking up something like myobj.something.something2. I'd hazard a guess that most of what you've been reading about the importance of caching are examples like this (since you mentioned jQuery):
var myButton = $('#my_button');
In such cases, caching the DOM references can pay dividends in speed on pages with a complex DOM. With your example, it'd probably just reduce the readability of the code by making you have to remember that currentObj is just an alias to another object. In a loop, that'd make sense, but elsewhere, it wouldn't be worth having another variable to remember.
The eval function is a powerful and easy way to dynamically generate code, so what are the caveats?
Improper use of eval opens up your
code for injection attacks
Debugging can be more challenging
(no line numbers, etc.)
eval'd code executes slower (no opportunity to compile/cache eval'd code)
Edit: As #Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.
eval isn't always evil. There are times where it's perfectly appropriate.
However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.
To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':
eval('document.' + potato + '.style.color = "red"');
If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:
document[potato].style.color = 'red';
...which is much easier to read as well as less potentially buggy.
(But then, someone who /really/ knew what they were doing would say:
document.getElementById(potato).style.color = 'red';
which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)
I believe it's because it can execute any JavaScript function from a string. Using it makes it easier for people to inject rogue code into the application.
It's generally only an issue if you're passing eval user input.
Two points come to mind:
Security (but as long as you generate the string to be evaluated yourself, this might be a non-issue)
Performance: until the code to be executed is unknown, it cannot be optimized. (about javascript and performance, certainly Steve Yegge's presentation)
Passing user input to eval() is a security risk, but also each invocation of eval() creates a new instance of the JavaScript interpreter. This can be a resource hog.
Mainly, it's a lot harder to maintain and debug. It's like a goto. You can use it, but it makes it harder to find problems and harder on the people who may need to make changes later.
One thing to keep in mind is that you can often use eval() to execute code in an otherwise restricted environment - social networking sites that block specific JavaScript functions can sometimes be fooled by breaking them up in an eval block -
eval('al' + 'er' + 't(\'' + 'hi there!' + '\')');
So if you're looking to run some JavaScript code where it might not otherwise be allowed (Myspace, I'm looking at you...) then eval() can be a useful trick.
However, for all the reasons mentioned above, you shouldn't use it for your own code, where you have complete control - it's just not necessary, and better-off relegated to the 'tricky JavaScript hacks' shelf.
Unless you let eval() a dynamic content (through cgi or input), it is as safe and solid as all other JavaScript in your page.
Along with the rest of the answers, I don't think eval statements can have advanced minimization.
It is a possible security risk, it has a different scope of execution, and is quite inefficient, as it creates an entirely new scripting environment for the execution of the code. See here for some more info: eval.
It is quite useful, though, and used with moderation can add a lot of good functionality.
Unless you are 100% sure that the code being evaluated is from a trusted source (usually your own application) then it's a surefire way of exposing your system to a cross-site scripting attack.
It's not necessarily that bad provided you know what context you're using it in.
If your application is using eval() to create an object from some JSON which has come back from an XMLHttpRequest to your own site, created by your trusted server-side code, it's probably not a problem.
Untrusted client-side JavaScript code can't do that much anyway. Provided the thing you're executing eval() on has come from a reasonable source, you're fine.
It greatly reduces your level of confidence about security.
If you want the user to input some logical functions and evaluate for AND the OR then the JavaScript eval function is perfect. I can accept two strings and eval(uate) string1 === string2, etc.
If you spot the use of eval() in your code, remember the mantra “eval() is evil.”
This
function takes an arbitrary string and executes it as JavaScript code. When the code in
question is known beforehand (not determined at runtime), there’s no reason to use
eval().
If the code is dynamically generated at runtime, there’s often a better way to
achieve the goal without eval().
For example, just using square bracket notation to
access dynamic properties is better and simpler:
// antipattern
var property = "name";
alert(eval("obj." + property));
// preferred
var property = "name";
alert(obj[property]);
Using eval() also has security implications, because you might be executing code (for
example coming from the network) that has been tampered with.
This is a common antipattern when dealing with a JSON response from an Ajax request.
In those cases
it’s better to use the browsers’ built-in methods to parse the JSON response to make
sure it’s safe and valid. For browsers that don’t support JSON.parse() natively, you can
use a library from JSON.org.
It’s also important to remember that passing strings to setInterval(), setTimeout(),
and the Function() constructor is, for the most part, similar to using eval() and therefore
should be avoided.
Behind the scenes, JavaScript still has to evaluate and execute
the string you pass as programming code:
// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);
// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);
Using the new Function() constructor is similar to eval() and should be approached
with care. It could be a powerful construct but is often misused.
If you absolutely must
use eval(), you can consider using new Function() instead.
There is a small potential
benefit because the code evaluated in new Function() will be running in a local function
scope, so any variables defined with var in the code being evaluated will not become
globals automatically.
Another way to prevent automatic globals is to wrap the
eval() call into an immediate function.
EDIT: As Benjie's comment suggests, this no longer seems to be the case in chrome v108, it would seem that chrome can now handle garbage collection of evaled scripts.
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
Garbage collection
The browsers garbage collection has no idea if the code that's eval'ed can be removed from memory so it just keeps it stored until the page is reloaded.
Not too bad if your users are only on your page shortly, but it can be a problem for webapp's.
Here's a script to demo the problem
https://jsfiddle.net/CynderRnAsh/qux1osnw/
document.getElementById("evalLeak").onclick = (e) => {
for(let x = 0; x < 100; x++) {
eval(x.toString());
}
};
Something as simple as the above code causes a small amount of memory to be store until the app dies.
This is worse when the evaled script is a giant function, and called on interval.
Besides the possible security issues if you are executing user-submitted code, most of the time there's a better way that doesn't involve re-parsing the code every time it's executed. Anonymous functions or object properties can replace most uses of eval and are much safer and faster.
This may become more of an issue as the next generation of browsers come out with some flavor of a JavaScript compiler. Code executed via Eval may not perform as well as the rest of your JavaScript against these newer browsers. Someone should do some profiling.
This is one of good articles talking about eval and how it is not an evil:
http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/
I’m not saying you should go run out and start using eval()
everywhere. In fact, there are very few good use cases for running
eval() at all. There are definitely concerns with code clarity,
debugability, and certainly performance that should not be overlooked.
But you shouldn’t be afraid to use it when you have a case where
eval() makes sense. Try not using it first, but don’t let anyone scare
you into thinking your code is more fragile or less secure when eval()
is used appropriately.
eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it.
This isn't related much to eval() function but this article has pretty good information:
http://blogs.popart.com/2009/07/javascript-injection-attacks/
If you are looking for the basics of eval() look here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
The JavaScript Engine has a number of performance optimizations that it performs during the compilation phase. Some of these boil down to being able to essentially statically analyze the code as it lexes, and pre-determine where all the variable and function declarations are, so that it takes less effort to resolve identifiers during execution.
But if the Engine finds an eval(..) in the code, it essentially has to assume that all its awareness of identifier location may be invalid, because it cannot know at lexing time exactly what code you may pass to eval(..) to modify the lexical scope, or the contents of the object you may pass to with to create a new lexical scope to be consulted.
In other words, in the pessimistic sense, most of those optimizations it would make are pointless if eval(..) is present, so it simply doesn't perform the optimizations at all.
This explains it all.
Reference :
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#eval
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#performance
It's not always a bad idea. Take for example, code generation. I recently wrote a library called Hyperbars which bridges the gap between virtual-dom and handlebars. It does this by parsing a handlebars template and converting it to hyperscript which is subsequently used by virtual-dom. The hyperscript is generated as a string first and before returning it, eval() it to turn it into executable code. I have found eval() in this particular situation the exact opposite of evil.
Basically from
<div>
{{#each names}}
<span>{{this}}</span>
{{/each}}
</div>
To this
(function (state) {
var Runtime = Hyperbars.Runtime;
var context = state;
return h('div', {}, [Runtime.each(context['names'], context, function (context, parent, options) {
return [h('span', {}, [options['#index'], context])]
})])
}.bind({}))
The performance of eval() isn't an issue in a situation like this because you only need to interpret the generated string once and then reuse the executable output many times over.
You can see how the code generation was achieved if you're curious here.
I would go as far as to say that it doesn't really matter if you use eval() in javascript which is run in browsers.*(caveat)
All modern browsers have a developer console where you can execute arbitrary javascript anyway and any semi-smart developer can look at your JS source and put whatever bits of it they need to into the dev console to do what they wish.
*As long as your server endpoints have the correct validation & sanitisation of user supplied values, it should not matter what gets parsed and eval'd in your client side javascript.
If you were to ask if it's suitable to use eval() in PHP however, the answer is NO, unless you whitelist any values which may be passed to your eval statement.
I won't attempt to refute anything said heretofore, but i will offer this use of eval() that (as far as I know) can't be done any other way. There's probably other ways to code this, and probably ways to optimize it, but this is done longhand and without any bells and whistles for clarity sake to illustrate a use of eval that really doesn't have any other alternatives. That is: dynamical (or more accurately) programmically-created object names (as opposed to values).
//Place this in a common/global JS lib:
var NS = function(namespace){
var namespaceParts = String(namespace).split(".");
var namespaceToTest = "";
for(var i = 0; i < namespaceParts.length; i++){
if(i === 0){
namespaceToTest = namespaceParts[i];
}
else{
namespaceToTest = namespaceToTest + "." + namespaceParts[i];
}
if(eval('typeof ' + namespaceToTest) === "undefined"){
eval(namespaceToTest + ' = {}');
}
}
return eval(namespace);
}
//Then, use this in your class definition libs:
NS('Root.Namespace').Class = function(settings){
//Class constructor code here
}
//some generic method:
Root.Namespace.Class.prototype.Method = function(args){
//Code goes here
//this.MyOtherMethod("foo")); // => "foo"
return true;
}
//Then, in your applications, use this to instantiate an instance of your class:
var anInstanceOfClass = new Root.Namespace.Class(settings);
EDIT: by the way, I wouldn't suggest (for all the security reasons pointed out heretofore) that you base you object names on user input. I can't imagine any good reason you'd want to do that though. Still, thought I'd point it out that it wouldn't be a good idea :)