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.
Related
For example:
module.exports = {
myLibraryFunction: function myLibraryFunction() {
...
}
}
The disadvantage is obvious. It's not very DRY, which means it can easily become out-of-sync if you're not careful. It also makes your code a little more verbose.
So what are the advantages? Is the tradeoff worth it?
I use this approach when writing JS libraries. The largest advantage is that tools like the Chrome debugger will have a definite name for your function as opposed to either "anonymous" or some name composed of the function path based on the variable names containing the function. If, however, you don't care about having method names when debugging, then it really comes down to a matter of taste. If you were to minify the resulting JS code, naming elements like that would get stripped out anyway.
As far as to how DRY this approach is, consider that the repeated names occur right next to each other. A quick copy & paste is all it takes to keep them in sync. It would be nice if a JS included a feature that causes a function to be named according to the variable it has been assigned to at the point of creation (or at least the ability to dynamically re-assign the function's name). Sadly, however, this is the only way JS allows for us to name these otherwise anonymous functions.
So my simple question is :
Which is the best solution ( performance and memory wise) in this case :
A. we process the variable into a new one and use it everywhere we need :
// imagine (a) is an incomming variable that
// we can't change or else we will break something
var a = "carrots";
var b = a.substr(0,a.length-1);
// and then use b everywhere
B. we process the variable on the fly:
// imagine (a) is an incomming variable that
// we can't change or else we will break something
var a = "carrots";
// and then use "a.substr(0,a.length-1);" everywhere
Please, it's not about how code is written ,is all about which one is faster and better.
Which one you choose and why?
Obviously the first approach is faster. Since we are calling a method and access a property, this is like magnitudes slower than just use/access a resulting string value.
Don't get me wrong, in absolute numbers this still seems like micro optimization, but in this universe and relation it's speed of light vs. a train.
By the way, the concept of storing and caching values in ECMAscript is very commonly used and right so (for different reasons like avoiding scope chains and prototype lookups).
Agreeing with jAndy. I just wanted to add an example and hopefully give another take.
The first approach is far faster.
Each time we call substring we will need to run through the string and create a new substring object on which to operate on in the future. We must run a method and create a new substring which is clearly more costly.
Think about it this way. You could do something (which costs the same amount as the other option lets say x ) one time, or do this x thing a theoretically unlimited time. You are looking at a cost of x vs infinity.
In theory you are potentially taking up less memory in the second. The var b will hold some memory (depends on the language) in java a string takes up 8 bytes. That will persist until the program closes. Instead if you substring each time you will create a value and then clean it once it is no longer used.
Does that make sense?
We create our var b and keep it around until the program closes (is no longer needed). Or we can create a variable a.substring but remove it when it is no longer needed. Technically depending on how the program works you may have less memory if you had say 100's of these over the entire process. However the memory used is negligible and garbage collection does not occur often enough (in normal conditions) for this to actually be true / relevant.
Memory saving is negligible and time complexity is comparatively significant.
Example A is far superior. Why would you in real life ever do the same thing many times if you can accomplish it by doing it just once?
I agree with jAndy.
The first example is going to be faster. You are caching the variable into b so the function you are calling on a is only called once. In your second example everytime you want to use a.substr() you will need to call the function.
So in the first example, you will call a.substr(0, a.length-1) once and cache the result to be used. In example two it will take n times as long where n is the number of times you are calling a.substr(0, a.length-1).
Depending on the what you are doing, there may be no noticeable difference at all. However, the first way is technically faster.
Also, as the comments on jAndy's answer suggest, it is better code since you do not need to repeated call a.substr(0, a.length-1), since you can just cache that.
It gets said a lot that local variables are faster than globals in JavaScript Eg:
function ()
{
// Local variable
var a = 9
}
For instance, I've been thinking of aliasing the global Math object to a local Mathl variable or alternatively aliasing specific (much used) functions to a local variable/function like Mathround() instead of using Math.round().
Now the things that I'm thinking of doing this with (eg Math.round() ) can be used plenty of times per animation frame (50ish) and there could be 60 frames per second. So quite a few lookups would be avoided if I do this. - and that's just one example of something I could do it with. There'd be lots of similar variables I could alias.
So my question is - is this really worth it? Is the difference tangible when there's so many lookups being avoided?
If you don't know whether it's worth it, then it's probably not. In other words, you should address performance issues when they happen by identifying, measuring, and testing situation-specific alternatives.
It's hard enough to write clear, readable, maintainable code when you set out to write something humans can understand. It's a lot harder if you set out trying to write something that computers can execute faster (before you even know what faster means in terms of your application). Focus on clarity and address performance problems as they arise.
As for your specific example. If you're dying to know the answer, then test it.
Lookups will be faster if you scope parent-scope variables locally. How much faster? Is the difference noticable? Only you can tell by measuring the performance of your code.
It isin't that rare to see the document being aliased to a local variable.
Have a look at this part of the ExtJS library for instance.
(function() {
var DOC = document,
However like already stated, beware blindly aliasing object member functions because you might run into this value issues.
E.g.
var log = console.log;
log('test'); //TypeError: Illegal invocation
//you could use bind however
log = console.log.bind(console);
Say you have this code:
for(...) {
someFunc();
var y = Math.cos(x);
...
}
To execute the Math.cos(x) the JS VM must a) compute location of global Math object and b) get cos property of it. Just in case someone inside that someFunc() doesn't do crazy things as this for example:
Math = {};
In general in JS access to local variable is similar (if not exact) to access to array element by known index. Access to global objects is pretty much always look-up by key in maps.
This may be a obvious question, but I was wondering if there was an efficiency difference between declaring something in a one time use variable or simply executing the code once (rather then storing it then using it). For example
var rowId = 3,
updateStuff(rowId);
VS
updateStuff(3);
I think that worrying about performance in this instance is largely irrelevant. These sorts of micro-optimizations don't really buy you all that much. In my opinion, the readability of the code here is more important, since it's better to identify the 3 as rowId than leaving it as a magic number.
If you are really concerned about optimization, minimizing your code with something like Google Closure would help; it has many tools that will help you make your code more efficient.
If you were using google closure to compile and if you annotated the var as a constant (as it appears in your example), I suspect the compiler would remove the constant and replace it with the literal.
My advice is to pick the readable option and if you really need the micro-optimizations and reduction in source size, use the google closure compiler or a minifier-- a tool is more likeley to accumulate enough micro-optimizations to make something noticeably faster, although I'd guess most of the saved milliseconds would come from reduced network time from minification.
And var declarations do take time and if you added that var to the global namespace, then there is one more thing that will be searched during resolving names.
With a modern browser that compiles your code, the generated code will be exactly the same unless the variable is referenced somewhere else also.
Even with an old browser if there is a difference it won't be something to worry about.
EDIT:
delete does not apply to non-objects, therefore my initial response was wrong. Furtermore since the variable rowId is declared with the flag var it will be cleaned up by the garbage collection. Was it on the other hand defined without, it would live for the duration of the page / application.
source: http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/
The variable rowId will be kept in memory and will not be released by the garbage collector since it's referenced to. Unless you release it afterwards like below it will be there till the end of the programs life. Also remember it take time to create the variable (minimal, but you asked)
var rowId = 3
updateStuff(rowId);
delete rowId
With efficiency in mind, then yes there is a difference. Your second example is the quickest and doesn't spend any extra resources.
OBS. Some languages do optimize code as such and simply remove the sequence, but I strongly doubt that JavaScript does so.
This is perhaps a dumb question, but I am new to Javascript and desperate for help.
If the Javascript engine will look for global variables outside of a function, then what is the point of passing parameters to it? What do you gain?
I understand that global variables are generally frowned upon, but I still don't understand the purpose of passing variables. Does it have something to do with data encapsulation?
There's a few magic words that are used by programmers to describe different kinds of functions. Here's a few:
Re-entrant
ThreadSafe
Referentially Transparent
Idempotent
Pure
Side-Effects
You can look some of them up if you want a headache. The point is that Computer science and engineering progress has always been about reducing complexity. We have spent quite a lot of time thinking about the best way to write a function to achieve that goal. Hopefully, you can stuff tiny bits of your program into your head at a time, and understand those bits, without having to also understand the overall functioning of the entire program simultaneously, or the detailed implementation of the insides of all the other functions. A function that uses global variables can't do that very well because:
You can't guarantee that the global variables exist
You can't guarantee that the global variables are what you think they are
You can't guarantee that other parts of the program haven't modified those variables in a way you didn't expect.
You can't easily generalise to use the function multiple times on multiple sets of variables.
You can't easily verify that the function works as advertised without first setting up the function's external environment and its dependencies.
If the global variables have changed in a way you didn't expect, it's really hard to track down which part of the program is the culprit. It could be any of 500 different functions that write to that variable!
On the other hand, if you explicitly pass in all the data a function needs to operate, and explicitly return all the results:
If something goes wrong with any of those variables, it's easy to find the source of the problem
It's easier to add code to verify the "domain" of your inputs. Is it really a string? Is it over a certain length, is it under a certain length? Is it a positive number? is it whole, or fractional? All these assumptions that your code needs to operate correctly can be explicit at the start of the function, instead of just crossing your fingers and hoping nothing goes wrong.
It's easier to guess what a particular function will actually do, if its output depends only on its input.
a function's parameters are not dependant on the naming of any external variables.
And other advantages.
if you were only going to use global variables that the functions worked on then you'd always have to know the inner workings of the functions and what your global variable names had to be for them to work.
also, something like Math.abs(n) would be hard to call twice in one line if using global variables.
Functions are reusable components of your code, that executes a particular snippet on the provided variable exhibiting varying behavior.
Encapsulation comes from being Object Oriented. Functions are more for giving structure to your program.
Also, you shouldn't undermine the execution time of a method, if the variable it access exists in the context rather than being global.
If you don't need parameters to be passed to functions, then, you really don't need functions.
Functions are usually (and should be) used to provide code re-use -- use the same function on different variables. If a function accesses global variables, then every time I use it it will perform the same action. If I pass parameters, I can make it perform a different action (based on those different parameters) every time I use it.
One of the main benefits is that it keeps all the information the function needs, nearby. It becomes possible to look at just the function itself and understand what its input is, what it does, and what its output will be. If you are using global variables instead of passing arguments to the function, you’ll have to look all over your code to locate the data on which the function operates.
That’s just one benefit, of many, but an easy one to understand.
Global variables (in any language) can sometimes become stale. If there is a chance of this it is good to declare, initialise and use them locally. You have to be able to trust what you are using.
Similarly, if something/someone can update your global variables then you have to be able to trust the outcome of what will happen whenyou use them.
Global variables are not always needed by everything so why keep them hanging around?
That said, variables global to a namesapce can be useful especially if you are using something like jquery selectors and you want to cache for performance sake.
Is this really a javascript question? I haven't encountered a language that doesn't have some form of global variables yet.