Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  192] [ 2]  / answers: 1 / hits: 109369  / 10 Years ago, mon, october 27, 2014, 12:00:00

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


More From » javascript

 Answers
3

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.


enter


[#68995] Friday, October 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
averyc

Total Points: 102
Total Questions: 113
Total Answers: 89

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;