Javascript variable what is less efficient - javascript

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.

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.

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);

Related

Solving simulataneous equations with Coffeequate

I'm looking for a Computer Algebra System to run in a browser, with a particular interest in finding roots to systems of equations.
I'm currently evaluating Coffeequate.
The simplest non-trivial system I came up with that wasn't on the demo page was a system of two simultaneous linear equations:
var exp1 = CQ('x = 2 * y + 6');
var exp2 = CQ('x - y = 10');
exp2.sub({x: exp1.solve('x')})
.solve('y');
Unfortunately, this hangs at the sub call.
What I would like to obtain is the value for all unknowns (i.e. x and y) that are knowable – there is guaranteed to be a solution in this case.
What am I doing wrong here?
CQ().solve returns an array of solutions (in case there are multiple solutions). However, things that you want to substitute in using CQ().sub have to be integers or CQ() objects themselves. The following code works:
var exp1 = CQ('x = 2 * y + 6');
var exp2 = CQ('x - y = 10');
exp2.sub({x: exp1.solve('x')[0]}).solve('y'); // 4
The fact that it actually hangs instead of erroring when you pass in an array is a bug; I'll patch that.
(Disclaimer: I wrote Coffeequate)

Draw graph without using eval()

I have created a Chrome extension that can draw the graph of the math equation user has inputted. To get the value of y easily, I used eval() (Yes I know it is bad) because the easiest way to achieve it.
var equ = $("#equ1").val(); //some element
//let's say equ = "2(2^x) + 3x"
//some magic code
//equ becomes "2*(pow(2,x))+3*x"
for(var x = -10; x < 10; x++){
var y = eval(equ.replace(/x/ig, x)); //calculate y value
drawPoint(x, y);
}
console.log("Graphing done.");
However, because of the new manifest version 2, I can't use eval anymore. I can't think of any way to manipulate the string. Any idea?
The clean way: You could try parsing the expression using Jison and building an AST from the input string. Then, associate functions with the AST node that apply the operations that the nodes represent to data given to them. This would mean that you have to explicitly put every math expression that you want to support in your grammar and your node code, but on the other hand, this would also make it easier to support mathematical operators that JS doesn't support. If you're willing to invest some time, this probably is the way to go.
The dirty way: If your extension is used on normal websites, you might be able to do some kind of indirect eval by injecting a <script> element into the website or so – however, that would likely be insecure.
Did you try New Function() ... ??
var some_logic = "2*(Math.pow(2,x))+3*x";
args = ['x', 'return (' + some_logic + ');'];
myFunc = Function.apply(null, args);
for (var x = -10; x < 10; x++) {
var y = myFunc(x);
console.log(x, y);
}
console.log("Graphing done.");
Fiddle - http://jsfiddle.net/atif089/sVPAH/

JSLint complaints when calculating squares as in a * a

When I write this Javascript code:
var a = 2;
var aSquared = a * a;
JSLint marks a * a as a weird assignment. It marks just the product, not the assignment (I'm using Netbeans 7.3).
I know I can use Math.pow(a, 2) but this kind of calculation takes place in a tight iterative numerical computation and the difference is relevant.
Is it really weird to calculate squares this way?
Personally, I'd just ignore it -- it's just a warning, and you know the code is good, so... meh.
But if you really want to avoid the warning, you could try wrapping some brackets around it:
var aSquared = (a * a);
Or you could replace your code with something like this:
function squared(a) { return a *= a; }

Is there anything more efficient than an array of objects in javascript to store large amounts of data?

My application gathers acceleration 10 times a second, therefore I have a need to store thousands of rows of data. Currently I have an object which is a list of other objects to store it all - anything more efficient than that?
var arr = [];
function dataPoint(x, y, z, tstamp) {
this.xAccel = x;
this.yAccel = y;
this.zAccel = z;
this.epoch = tstamp;
}
var dp = new dataPoint( acceleration.x, acceleration.y, acceleration.z, acceleration.timestamp );
arr.push(dp);
If the platform you're targeting supports typed arrays then those would probably be more efficient.
Specification
MDN's documentation
Looking at your code:
> var arr = [];
> function dataPoint(x, y, z, tstamp) {
> this.xAccel = x;
> this.yAccel = y;
> this.zAccel = z;
> this.epoch = tstamp;
> }
> var dp = new dataPoint( acceleration.x, acceleration.y,
> acceleration.z, acceleration.timestamp );
> arr.push(dp);
I don't see why you're bothering with a constructor, you could simply do (abbreviated):
arr.push({x: acc.x, y: acc.y, z: acc.z, epoch: acc.timestamp});
though I'd probably change epoch to t. And given that you have such as simple structure, why not:
arr.push([acc.x, acc.y, acc.z, acc.timestamp]);
and reference the members by index. The advantage of a constructor is inherited methods, but if you only have one level of inheritance, simple functions are just a effective and probably faster to execute (lookups on the global object are generally very fast compared to [[Prototype]] chains, but see the caveat below)
Incidentally, I think the name epoch is being used in the wrong context. An epoch is a reference point, so you might have an epoch of say 2012-04-20T18:53:21.098Z and then have deltas from that in units like milliseconds or seconds. The epoch for javascript time references (i.e. the value returned by Date.prototype.getTime) is 1970-01-01T00:00:00Z, the time reference is a delta from that.
Caveat
In regard to what is "best", I presume your criterion is "fastest", with the caveat that the code must still be reasonably clear and maintainable. Your best bet there is to avoid obvious speed issues, then test in a wide variety of browsers and optimise based on results. An optimisation in one browser may have little or no difference in others, or may be significantly slower. e.g. decrementing loops used to be faster in most browsers, but much slower in Opera. Also, evaluating expressions in loop conditions, like:
while ((el = node.firstChild))
were once much slower than:
while (el) {
el = node.firstChild
but it doesn't seem to matter as much with newer browsers. Similarly, for loops are just as fast (generally) as while and do loops. but take more typing to setup.

Optimise my Javascript percentage calculator

I have a javascript that calculates the percentage from two fields (retail and network) and then dumps that percentage into another field (markup).
As I am relatively new to the world of JS I have ended up reusing the code for several rows of fields. This goes against DRY and KISS principles so I was wondering if you could give me some input on how to optimise my code so that it can handle any two fields and then dump a value to a third field.
Here is a screenshot of my form segment that is using it.
http://i.imgur.com/FHvDs.png
Here is my code I am using, I have had to reuse it four times and place the code in four functions e.g. (percentage1, percentage2, percentage3, percentage4) each one of these functions deals with a row of fields show in the screenshot.
function percentage1()
{
//the dividee
x = document.getElementById('tariff_data');
//the divider
y = document.getElementById('network_data');
//if the first value is lower than the second, append a "-" sign
if (x.value < y.value)
{
z = "-"+(x.value/y.value)*100;
document.getElementById('markup_data').value = z;
}
//not a negative percentage
else
{
z = (x.value/y.value)*100;
document.getElementById('markup_data').value = z;
}
}
function percentage2()
{
//the dividee
x = document.getElementById('tariff_rental');
//the divider
y = document.getElementById('network_rental');
//if the first value is lower than the second, append a "-" sign
if (x.value < y.value)
{
z = "-"+(x.value/y.value)*100;
document.getElementById('markup_rental').value = z;
}
//not a negative percentage
else
{
z = (x.value/y.value)*100;
document.getElementById('markup_data').value = z;
}
}
etc etc....
These functions are called using the onchange HTML attribute
Also when I divide by a decimal number it gives the wrong value, any Ideas how to make it calculate the correct percentage of a decimal number?
My code also gives out these strange outputs:
NaN , Infinity
Thanks
Rather than optimization, let's focus on correctness first =)
Note that the HTMLInputElement.value property has type "string", so your arithmetic operators are doing implicit type conversion which means you are likely often doing string concatenation instead of the numeric operations you expect.
I strongly recommend explicitly converting them to numbers first and checking for invalid input, also, don't forget to declare your variables first using var so they don't potentially clobber globals, e.g.:
var x = Number(document.getElementById('tariff_data'));
var y = Number(document.getElementById('network_data'));
if (!isFinite(x) || !isFinite(y)) {
// Handle non-numerical input...
}
You can also use the parseFloat function if you prefer, e.g.:
var x = parseFloat(document.getElementById('tariff_data'), 10);
I highly recommend doing some formal learning about the JavaScript language; it is full of pitfalls but if you stick to the "good parts" you can save yourself a lot of hassle and headache.
With regard to DRYing your code out; remember that you can:
Pass parameters to your functions and use those arguments within the function
Return values using the return keyword
In your case, you've got all your multiplication code repeated. While trying to fix the string vs. number problems maerics has already mentioned, you could do something like this:
// We're assuming 'dividee' and 'divider' are numbers.
function calculatePercentage(dividee, divider) {
var result;
// Regardless of the positive/negative result of the calculation,
// get the positive result using Math.abs().
result = Math.abs((dividee.value / divider.value) * 100);
// If the result was going to be negative...
if (dividee.value < divider.value) {
// Convert our result to negative.
result = result * -1;
}
// Return our result.
return result;
}
Then, in your percentage functions, you can just call this code like so:
function percentage1() {
var tariff, network, markup;
tariff = parseFloat(document.getElementById('tariff_data').value, 10);
network = parseFloat(document.getElementById('network_data').value, 10);
markup = document.getElementById('markup_data');
markup.value = calculatePercentage(tariff, network);
}
Obviously, you could take this further, and create a function which takes in the IDs, extracts the values from the elements etc., but you should try and build that yourself based on these tips.
Maerics also makes a very good point which you should take note of; learn more about the Good Parts of JavaScript. Douglas Crockford's book is excellent, and should be read and understood by all JS developers, IMHO.
Hope this helps you clean your code up!

Categories