6

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

Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153

1 Answers1

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.com/...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.

Broxzier
  • 2,909
  • 17
  • 36
  • Nice to know jsperf, I had no clue on how to profile javascript. The legibility sacrifice may be worth since it is from a distance function that will be applied to potentially lengthy arrays. – Paulo Scardine Aug 22 '13 at 14:39
  • @PauloScardine If you plan to use it a lot, screw the legibility. You can always add comments to explain what that line of code does. I had to read it a couple of times before I got it. – Broxzier Aug 22 '13 at 14:42
  • This code is from Mike Bostock of D3 fame, it is way beyond my wizardry level. Thanks for the answer. :-) – Paulo Scardine Aug 22 '13 at 14:46
  • How does this compare to `exp` ? – Flame_Phoenix Jul 29 '16 at 11:35