python vs php, python much slower in basic loops/arithmetic
<p>I am in the process of trying to speed up my python application and have found there are small blocks of seemingly trivial code that take a surprising amount of time.  I wrote a very very simple benchmark to test the speed of loops, casting and arithmetic.  I have a few variants (with types) that all boil down to adding 4+4 one million times:</p>

<p><strong>Python</strong></p>

<pre><code>import time;

#test 1
v=4
t=time.time();
for i in range(1000000):
    val=v+v
print (time.time()-t), "simple addition";

#test 2
v="4"
t=time.time();
for i in range(1000000):
    val=int(v)+int(v)
print (time.time()-t), "cast string to int addition";
</code></pre>

<p>The times taken for this, in order are:</p>

<pre><code>0.293562889099 simple addition
2.72776389122 cast string to int addition
</code></pre>

<p><strong>PHP</strong></p>

<p>I wrote two php tests that correspond to #1 and #2 above</p>

<pre><code>#test 1
$time_start = microtime(TRUE);
$val=4; //an int
for($i=0;$i&lt;1000000;$i++){
    $v=$val+$val;
}
echo (microtime(TRUE) - $time_start)." seconds for int addition\n";

#test 2
$time_start = microtime(TRUE);
$val="4"; //a string
for($i=0;$i&lt;1000000;$i++){
    $v=$val+$val;
}
echo (microtime(TRUE) - $time_start)." seconds to cast strings to int, then addttion\n";
</code></pre>

<p>This comes back with:</p>

<pre><code>0.083414077758789 seconds for int addition
0.28849601745605 seconds to cast strings to int, then addition
</code></pre>

<p>Test one shows PHP being <strong>~3 times</strong> faster with int addition, and test two shows PHP being <strong>~10 times faster</strong> with casting a string to an int and adding it. </p>

<p>Are my tests fair? Are there any fundamental differences between them that would account for such a huge disparity?  To be honest, I tried the Python stuff a few different ways (<code>while</code> loop instead of <code>for in</code>, different casting, etc) and this was the <em>best</em> I could do.</p>

<p>I understand there are lies, damned lies, and benchmarks, and you should test your specific use case and not contrived benchmarks .... well my use case has long loops, integer arithmetic and string->int casting, so this seems very relevant to my use case.</p>

<p><strong>C++</strong></p>

<p>For fun, I dusted off my college skills and wrote a cpp version, disclaimer, I am very rusty, so be kind :)</p>

<pre><code>#include &lt;cstdlib&gt;
#include &lt;string&gt; 
using namespace std;


int main(){
    std::string v = "4";
    int i;
    for (i = 0; i &lt; 1000000; i++){
        int val = atoi(v.c_str())+atoi(v.c_str());
    }
    return 0;
}
</code></pre>

<p>It is similar to test #2 above with a casting a string to an int and adding.  It took .1 seconds representing a 27 fold speed increase over the python test case and a 3 fold increase over the php test case.</p>
