samid
samid

Reputation: 3

Javascript variable what is less efficient

I am learning Javascript currently.I was wondering if there is any difference between:

var factor=0.1;
var limit=10;
var x;
var y;

x= limit*factor;
y= limit*factor;

//or
var limit=10;
var x;
var y;

x=limit *0.1;
y=limit*0.1;

Does it make any difference (when looking at performance for example)? If so, why it is different? The second example looks less promising to me, because I keep thinking that I am declaring the variable 0.1 twice. Thanks for your help in advance.

Upvotes: 0

Views: 80

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

There is a very small difference. When you use factor in the two multiplications, the JavaScript engine has to go look up the value of factor in the current lexical environment object each time — in theory, anyway; optimization may well be able to get rid of that, if and when the code is chosen for optimization by the JavaScript engine.

But regardless: Worry about performance problems when you have a performance problem to worry about. Instead, concentrate on readability and maintainability. If x and y are meant to be multiplied by the same value, put that value in something (a var, or perhaps a const with ES2015+), and use it in both places.

Upvotes: 2

Mr. Alien
Mr. Alien

Reputation: 157434

I would suggest you go ahead with the first example, but with a modification. Variables are meant to hold dynamic data, it is better to hold 0.1 in a variable, so you can change it over time if required.

// have a function so that you don't repeat the code
function getFactor(factor, limit) {
  return limit * factor;
}

//declare the variables and set the required default values
var factor = 0.1,
    limit = 10,
    x, y;

//assign getFactor to x and y variables
x = y = getFactor(factor, limit);

Upvotes: 0

Related Questions