最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is Math.pow more expensive than multiplication using temporary assignments? - Stack Overflow

programmeradmin4浏览0评论

When porting a javascript library to Python, I found this code:

return Math.atan2(
    Math.sqrt(
       (_ = cosφ1 * sinΔλ) * _ + (_ = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * _
    ), 
    sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ
);

Am I wrong or (_ = cosφ1 * sinΔλ) * _ could be written like Math.pow(cosφ1 * sinΔλ, 2)?

I guess the author is trying to avoid using Math.pow, is this expensive in javascript pared to the temporary assignment?

[update]

As of late 2016, with Chrome 53.0 (64-bit) looks like the difference is not as large as it used to be.

When porting a javascript library to Python, I found this code:

return Math.atan2(
    Math.sqrt(
       (_ = cosφ1 * sinΔλ) * _ + (_ = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * _
    ), 
    sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ
);

Am I wrong or (_ = cosφ1 * sinΔλ) * _ could be written like Math.pow(cosφ1 * sinΔλ, 2)?

I guess the author is trying to avoid using Math.pow, is this expensive in javascript pared to the temporary assignment?

[update]

As of late 2016, with Chrome 53.0 (64-bit) looks like the difference is not as large as it used to be.

Share Improve this question edited Oct 21, 2016 at 21:18 Paulo Scardine asked Aug 22, 2013 at 14:13 Paulo ScardinePaulo Scardine 77.5k12 gold badges131 silver badges153 bronze badges 3
  • Why dont you try it out at jsperf and let us know. – atomman Commented Aug 22, 2013 at 14:31
  • @atomman: nice to know about jsperf, thanks – Paulo Scardine Commented Aug 22, 2013 at 14:47
  • jsben.ch/#/lhQpz check it here – EscapeNetscape Commented Oct 21, 2016 at 21:03
Add a ment  | 

1 Answer 1

Reset to default 10

The only reason I can think of is performance. First let's test if they actually do the same and we didn't overlook something.

var test = (test = 5 * 2) * test; // 100
Math.pow(5 * 2, 2); // 100

As expected, that's proven to do the same. Now let's see if they have different performances using jsperf. Check it out here: http://jsperf./...num-self

The differences for Firefox 23 are very small, but for Safari the difference was much bigger. Using Math.pow seems to be more expensive there.

发布评论

评论列表(0)

  1. 暂无评论