

Ask HN: Strange execution times of Javascript and PHP - icode

Hello HN,<p>just for fun I executed this in javascript:<p><pre><code>  function test()
  {
   var r=1;
   for (var i=0;i&#60;10000000;i++)
   {
    r*=1.0000001;
   }
   return r;
  }
  var start = (new Date).getTime();
  test();
  diff = (new Date).getTime() - start;
</code></pre>
that gives me about 80ms<p>And this in PHP:<p><pre><code>  function test()
  {
   $r=1;
   for ($i=0;$i&#60;10000000;$i++)
   {
    $r*=1.0000001;
   }
   return $r;
  }
  $start = microtime(true)*1000;
  $r=test();
  echo "$r\n";
  $stop = microtime(true)*1000;
  echo $stop-$start."\n";
</code></pre>
That gives me about 1300 ms on the command line and about 5000 ms when executed by apache.<p>Any ideas to explain these differences?
======
Khao
I just hosted your php script over here : <http://khao.kodingen.com/test.php>
and it's a lot faster but still not perfect. I get about 721ms when I run it
and when I run the javascript version in firebug it's a lot slower : 1188ms.

I guess the browser you're using is compiling the javascript more efficiently
(probably by doing some kind of crazy optimization in the for loop) while PHP
is not as good for optimizing for loops.

~~~
icode
When you compare the PHP with the Javascript version, do you do it on the same
machine? It sounds like you run the PHP on the Server and the JS on your
client.

My question was: Why is the Javascript version 20 times faster on the same
machine. I mean.. 20 is a really big factor.

~~~
Khao
No it's not the same machine as I don't have any php running on my pc right
now. However, I just tried the same javascript snippet in the Chrome console
and it takes 179ms instead. As I said, it's a matter of optimization that is
happening with the interpreter (Chrome doesn't run javascript the same way
Firefox does, as not every php version will interpret php code the same way
based on different versions and compile options)

Edit : Think about that : web browser are always on the cutting edge of
javascript performance with the ton of javascript libraries that keep popping
out each day. Everytime a new browser comes out, tons of bloggers test the
javascript speed of those browsers so there is a lot of work going into
optimizing javascript to make it as lightning-fast as possible.

On the other hand, PHP hasn't been pushed like that towards compile-time
optimization so that's why Javascript can sometimes beat PHP in terms of speed
tests.

