In Javascript, which operator is faster, the '*' multiply or '/' divide? - javascript

In javascript, is there a speed advantage between the multiplication operator and the division operator? As an example...
var foo = bar * 0.01;
var foo = bar / 100;
foo is the same for both, but which statement returns the value of foo the fastest? I know this may be an incredibly small difference, however, when loop processing large amounts of data it could make a bigger difference than realized, which would then make a difference in how I construct equations to facilitate the processing.

I would say, it depends on the implementation. I would just make an own test somehow or try to google it.
For most machines, multiplications is faster, but the raw CPU speed is not decisive when it comes to scripting languages. Even when the implementation is the same, the execution time for one or the other will not differ so much, since the overhead of scripting languages is normally much bigger.
Normally the difference between different operations is so small, that it is not worth it to think about it. When you must, you probably are using the wrong language, anyhow.

In computer systems, the only basic operators are + (adders) and (*) multipliers. You either add (negative or positive) numbers or rotate numbers (either left or right for multiplication and division respectively). You should be able to work it out whether multiplication or division takes longer...
*btw...unless I am wrong, your question has nothing to do with javascript. Javascript is an interpreted language with engines such as spidermonkey or rhino....
FYI You should read this - directly from the main people....to have better insight of "what" might be happening.

Related

What's the fastest way to square a number in JavaScript?

What's the fastest way to square a number in JavaScript?
function squareIt(number) {
return Math.pow(number,2);
}
function squareIt(number) {
return number * number;
}
Or some other method that I don't know about. I'm not looking for a golfed answer, but the answer that's likely to be shortest in the compiler, on the average.
Edit: I saw Why is squaring a number faster than multiplying two random numbers? which seemed to indicate that squaring is faster than multiplying two random numbers, and presumed that n*n wouldn't take advantage of this but that Math.pow(n,2) would. As jfriend00 pointed out in the comments, and then later in an answer, http://jsperf.com/math-pow-vs-simple-multiplication/10 seems to suggest that straight multiplication is faster in everything but Firefox (where both ways are similarly fast).
Note: Questions like this change over time as browser engines change how their optimizations work. For a recent look comparing:
Math.pow(x1, 2)
x1 * x1
x1 ** 2 // ES6 syntax
See this revised performance test and run it in the browsers you care about: https://jsperf.com/math-pow-vs-simple-multiplication/32.
As of April 2020, Chrome, Edge and Firefox show less than 1% difference between all three of the above methods.
If the jsperf link is not working (it seems to be occasionally down), then you can try this perf.link test case.
Original Answer from 2014:
All performance questions should be answered by measurement because specifics of the browser implementation and the particular scenario you care about are often what determine the outcome (thus a theoretical discussion is not always right).
In this case, performance varies greatly by browser implementation. Here are are results from a number of different browsers in this jsperf test: http://jsperf.com/math-pow-vs-simple-multiplication/10 which compares:
Math.pow(x1, 2)
x1 * x1
Longer bars are faster (greater ops/sec). You can see that Firefox optimizes both operations to be pretty much the same. In other browsers, the multiplication is significantly faster. IE is both the slowest and shows the greatest percentage difference between the two methods. Firefox is the fastest and shows the least difference between the two.
In ES6 you can do the following with Exponentiation (x ** y), which produces the same result as Math.pow(x,y):
function squareIt(number) {
return number ** 2;
}
console.log(squareIt(5));
or you can use a JavaScript library called BigInteger.js for the purpose.
alert(bigInt(5).square());
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>
In general, x * x is either much faster than or about the same as a pow() call in any language. pow() is a general exponential designed to work with floating point arguments, and it usually uses a calculation that has a lot more operations than a single multiplication. It's notoriously slow. Some pow() implementations will helpfully filter out integer powers for special evaluations, like for x^4 it might do x2=x * x, x4=x2 * x2, but adding special conditions like that can slow down the general implementation, and the x * x vs. pow() rule is so well known among programmers you can't really count on the library implementation to help you out. This is standard advice in numerical analysis: never use pow() for x^2 (or x^.5). At best, it's no slower than the pow implementation, if it's optimized out as x * x at compile time, and at worst, it's horribly slower (and probably not as accurate either). You could go and test it on every possible platform you expect your code to run on, but in real life, there's no good reason to use pow() for squares. There can be good reasons to write a convenience function that does x * x, but if the language allows it, it's a good idea to make sure that it's marked up so that there's no actual function call going on at the machine level. Unfortunately, I don't think Javascript has anything like that, but I suspect that the JIT compilers are usually smart enough to render short functions like that without a jump.
Regarding the issue of x * x vs. x * y, the former would often be faster simply because it avoids a MOV at the machine level (aside from the considerations in the post you referenced), but it's pretty certain that the JS engine is smart enough not to do an extra MOV if the operand is already in a register. It's not going to load x from memory and then load it from memory again, or move it from one register into another. That's a basic behavior of optimizing compilers. You have to keep in mind that the compiler is going to do a lot of rearranging and consolidation of algebraic operations, so when you write x * x, a lot of things could be going on depending on what happened to x previously or happens to it later. This is another reason to avoid pow(), since the optimizer can do a lot of tricks with x * x that may not be available if it does a pow() call instead. Again, you can hope that it intelligently inlines pow(x,2) to x * x, but don't count on it.

What comparison operators are more processor efficient: <, <=, != or ==?

I have the choice between types of comparison operations, please put them in the order of efficiency for the processor starting with the most efficient:
if (x == 1)
if (x != 0)
if (x < 2)
if (x <= 3)
Often I am faced with case where I can use any of them I choose for the same outcome...
This is something I've always wanted to know and probably some other people want to know it too. Also, does it vary for different programming languages or not?
Edit: Thanks for the information. Because they are apparently all the same efficiency this means I can use more > or < type operators in order to catch glitches better!
Usually, any of them is more efficient than the others. This is because on most CPUs, they map to specialized opcodes, whose execution is handled by the very same physical unit, in slightly different configurations. Using a non-existent but very simple to understand assembly syntax, each branch (if condition) might translate to:
if (x == 1)
test = x - 1
branch_equal_zero test
if (x != 0)
test = 0
branch_non_equal_zero test
if (x < 2)
test = x - 2
branch_lower_than_zero test
if (x <= 3)
test = x - 3
branch_lower_or_equal_to_zero test
As you can see, comparing to zero (regardless of the comparision) might be faster because there is no subtraction involved -- but faster of such a tiny fraction of second you might notice it only under extremely heavy load.
Even if we are speaking of interpreted languages (PHP and JS), the answer does not change, because all operators are directly mapped to the underlying native comparisions by the interpreters. Let alone any type cast or intermediate conversion that might take place.
The simple answer is "They are all the same", because, at the basic level, they are all the same. Also, they are all so blazingly fast, you won't notice the difference anyway.
I can see how one may be quicker than the other - CPUs tend to reorder instructions and predict branches - so in specific cases there may be a difference.
However, none if these cases applies to anything you do in JavaScript. In JavaScript you can be very certain they are all the same.
Let's put it differently, starting from the higher level.
Javascript and PHP, both of them are high level language, and so won't use CPU directly but over many processes already thought to optimize what you write. In Javascript that "process" is called Javascript Engine. In PHP it is the interpreter itself. Don't misunderstand me, they are thought to do their work leaving "a bit" of care on optimization.
So in the end the real way to optimize this kind of operation would be to find a real big issue in PHP or Javascript Engine itself.
Now let's face the lowest aspect of these operators. A modern CPU has 3.2GHz (or even more) clock speed. So, it would mean 3200000000 operations per second, which is a huge number. Suppose those operation (which in the end are almost all the same) use 2 or 3 ticks. it would take you about 10^9 operators to notice a significative difference.

Optimizing javascript code to use integer arithmetic

There are some algorithms which solve problems "very well" under the assumption that "very well" means minimizing the amount of floating point arithmetic operations in favor of integer arithmetic. Take for example Bresenham's line algorithm for figuring out which pixels to fill in order to draw a line on a canvas: the guy made practically the entire process doable with only some simple integer arithmetic.
This sort of thing is obviously good in many situations. But is it worth fretting about operations that require a lot of floating-point math in javascript? I understand that everything's pretty much a decimal number as far as the language specification goes. I'm wondering if it is practically worth it to try to keep things as integer-like as possible--do browsers make optimizations that could make it worth it?
You can use Int8, Uint8, Int16, etc. in javascript, but it requires a bit more effort than normal - see TypedArrays.
var A = new Uint32Array(new ArrayBuffer(4*n));
var B = new Uint32Array(new ArrayBuffer(4*n));
//assign some example values to A
for(var i=0;i<n;i++)
A[i] = i; //note RHS is implicitly converted to uint32
//assign some example values to B
for(var i=0;i<n;i++)
B[i] = 4*i+3; //again, note RHS is implicitly converted to uint32
//this is true integer arithmetic
for(var i=0;i<n;i++)
A[i] += B[i];
Recently, the asm.js project has made it is possible to compile C/C++ code to strange looking javascript that uses these TypedArrays in a rather extreme fashion, the benefit being that you can use your existing C/C++ code and it should run pretty fast in the browser (especially if the browser vendors implement special optimizations for this kind of code, which is supposed to happen soon).
On a side note* if you program can do SIMD parallelism (see wikipeda), i.e. if your code uses the SSEx instruction set, your arithmetic will be much faster, and in fact using int8s will be twice as fast as using int16s etc.
*I don't think this is relevant to browsers yet due to being too difficult for them to take advantage of on the fly. Edit: It turns out that Firefox is experimenting with this kind of optimization. Also Dart (true Dart, not Dart compiled to js) will be able to do this in Chrome.
Long ago, computers lacked dedicated FPUs and did floating point math entirely via software emulation.
Modern computers all have dedicated FPUs which handle floating point math just as well as integer. You should not need to worry about it unless you have a very specific circumstance.
Actually, it makes no different. JavaScript has no concept of "integer". JS only uses double-precision floating-point numbers, which may or may not be integers.
Therefore, there is absolutely nothing to gain in terms of performance by limiting yourself to integers.
However, keep in mind that integers will be precise up to 251, whereas non-integers can very easily suffer from precision loss (example: 0.1), so you might gain because of this.

Bitwise operations' significance in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Where would I use a bitwise operator in JavaScript?
In c/c++ bitwise operations are faster than normal(arithmetic) operations(significant atleast in low performance processors). Does the same apply in js? I don't think as the reason its faster in c is bitwise operations are hardwired and usually are completed in 1 processor cycle. But js runs within browser which doesn't have any such hardware(registers I mean) access. I am not sure (around 70% sure :) ). What are typical(or some smarter) uses of bitwise operators (especially in js but I would like to know others too). Please correct me if I am wrong anywhere.
Some bitwise operators are faster than arithmetic operators in some cases. It's hard to optimise Javascript, because the performance varies greatly betwen browsers, platforms and computer models.
Modern browsers compile the Javascript code into native code, so some things that are said about compiled languages are also relevant for Javascript. However, some things that are said about compiled languages are getting more and more inaccurate with newer processors. It's for example not relevant to look at the performance of a single processor operation any more, as operations are run in parallel. You don't look at how many cycles an operation takes any more, but how many operations you can do in a cycle.
To determine if a specific operation is faster or slower than another in Javascript, you would have to test it on a wide variety of computers and browsers, and look at the average, best case and worst case. Even then, any specific result that you get, woudl get more and more out of date for each new browser version that is released.
Bitwise operators in JS are slow. Really slow compared to C. The reason is that in JS, all numbers are represented as double-precision floating point numbers, so to perform a bitwise operation, the runtime has to convert them to 32-bit integers and back.
That's not to say they aren't useful. e.g., Node#compareDocumentPosition returns a bitmask, and something.length >>> 0 is a common way of getting the length property of something or zero if length isn't a number or is NaN. Also, a / b | 0 is a fast way to do Math.floor(a / b), assuming a and b are >= 0.

Performance of bitwise operators in javascript

One of the main ideas behind using bitwise operators in languages like C++/java/C# is that they're extremely fast. But I've heard that in javascript they're very slow (admittedly a few milliseconds probably doesn't matter much today). Why is this so?
(this question discusses when bitwise operators are used, so I'm changing the focus of this question to performance.)
This is quite an old question, but no one seemed to answer the updated version.
The performance hit that you get with JavaScript that doesn't exist in C/C++ is the cast from floating point representation (how JavaScript strores all of its numbers) to a 32 bit integer to perform the bit manipulation and back.
Nobody uses hex anymore?
function hextoRgb(c) {
c = '0x' + c.substring(1);
return [(c >> 16) & 255, (c >> 8) & 255, c & 255];
}
var c1 = hextoRgb('#191970');
alert('rgb(' + c1.join(',') + ')');
I use bitwise shift of zero in JS to perform quick integer truncation:
var i=3.141532;
var iTrunc=i>>0; //3
When would you want to use them? You would want to use them when you want to do bitwise operations. Just like you'd use boolean operators to do boolean operations, and mathematical operators to do mathematical operations.
If you are comfortable with bitwise operators it is very natural to use them for some applications. They can be used for many purposes other than an over-optimized boolean array. Of course, these circumstances don't come up very often in Javascript programming, but that's no reason why the operators shouldn't be available.
I found some good info #
http://dreaminginjavascript.wordpress.com/2009/02/09/bitwise-byte-foolish/
Apparently they perform very well these days. Why would you use them? Same reason you would anywhere else.
I'd think it's up to the implementer to make an operator efficient or inefficient. For example, there's nothing that prevents a JavaScript implementer from making a JITting VM, which turns a bitwise op into 1 machine instruction. So there's nothing inherently slow about "the bitwise operators in JavaScript".
There is an NES emulator written in JavaScript - it seems to make plenty of use of bitwise operations.
I am doubtful that bitwise operation are particularly slow in javascript. Since such operations can map directly to CPU operations, which are themselves quite efficient, there doesn't appear to be any inherent characteristic of bitwise operations that would force them to be irremediably slow in javascript.
Edit December 2015: I stand corrected! The performance hit that Javascript suffers in regards to bitwise operations comes from the need of converting from float to int and back (as all numeric variables in Javascript are stored as floating point values). Thank you to Chad Schouggins for pointing that out.
Never the less, as indicated in several responses, there exist various applications of javascript which rely on bitwise operation (ex: crytography and graphics) and which are not particularly slow... (see silky and Snarfblam on this page). This suggests that while slower than C/C++ and other languages which translate directly bitwise ops to single native CPU instructions, bitwise operations are all that sluggish.
Let's never the less entertain the possibility that some particular reasons caused the various implementers of javascript hosts to implement bitwise ops in a fashion that makes these extremely slow, and see if this even matters...
Although javascript has been used for other purposes, the most common use of this language in in providing user interface type of services.
BTW, I do not mean this in any pejorative way at all; performing these smart UI functions, and considering various constraints imposed on the language and also the loose adherence to standards, has required -and keeps requiring- talented javascript hackers.
The point is that in the context of UI-type requirements, the need for any quantity of bitwise operations susceptible of exposing the slowness of javascript in handling such operations is uncommon at best. Consequently, for typical uses, programmers should use bitwise operations where and if this approach seems to flow well with overall program/data and they should do so with little concern for performance issues. In the unlikely case of performance bottleneck arising from bitwise use, one can always refactor things, but one is better off staying clear from early optimization.
The notable exception to the above is with the introduction of canvas, on modern browsers, we can expect that more primitive graphic functions will be required of javascript hosts, and such operations can require in some cases heavy doses of bitwise operations (as well as healthy does of math functions). It is likely that these services will eventually be supported by way of javascript libraries (and even end-up as languages additions). For such libraries the common smarts of the industry will have been put to use to figure out the most efficient approaches. Furthermore and if indeed there is a weakness in javascript performance with bitwise ops, we'll get some help, for I predict that the javascript implementations on various hosts (browsers) will be modified to improve this particular area. (This would follow the typical pattern of evolution of javascript, that we've seen over the years.)
When speed is paramount, you can use them for bit-masking: http://snook.ca/archives/javascript/storing_values/
Also, if you need to support Netscape 4, you'd use them to deal with Document.captureEvents(). Not that any respectable company would have you write JS for NS4...
People do interesting things in JavaScript.
For example there are a lot of cryptography algorithms implemented in it (for various reasons); so of course bitwise operators are used.
Using JavaScript in its Windows Scripting Host JScript incarnation, you might have cause to use bitwise operators to pick out flags in values returned from WMI or Active Directory calls. For example, the User Access value of a user's record in AD contains several flags packed into one long integer.
ADS_UF_ACCOUNTDISABLE = 0x00000002;
if (uac & ADS_UF_ACCOUNTDISABLE == ADS_UF_ACCOUNTDISABLE) {
// user account has been disabled
}
Or someone's arbitrary table structure may contain such a field, accessible through ADO with JScript.
Or you may want to convert some retrieved data into a binary representation on any platform, just because:
BinaryData = "L";
BinaryString = BinToStr(BinaryData, ".", "x");
// BinaryString => '.x..xx..'
So there are numerous reasons why one might want to do bit manipulation in JavaScript. As for performance, the only way to know is to write it and test it. I suspect in most cases it would be perfectly acceptable, not significantly worse than any other of the multitude of inefficiencies these systems contain.
A lot of bitwise operations are being benchmarked here: http://jsperf.com/rounding-numbers-down/3
However, feel free to create your own performance testcase on jsPerf!

Categories

Resources