Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory consumption on an iteration script

I have a script written in PHP and the same script written in Javascript.
It iterates a million times and on each time strips a string into an array and assigns the first array item into a new variable.

The PHP is:

class First
{
public function Iterate()
{
    $count = 1000000; 
    $test_string = '';
    $test_array = '';
    $first_word = '';
    for($i=1; $i <= $count; $i++){
        $test_string = 'This is a test string';
        //could use explode but no explode in js
        $test_array = split(" ", $test_string);
        $first_word = $test_array[0];
    }
}
}
$first = new First();
$first->Iterate();

And the Javascript is:

function First() {
this.Iterate = function() {
    count = 1000000;
    test_string = '';
    test_array = '';
    first_word = '';
    for(var i=1;i <= count; i++){
                    test_string = 'This is a test string';
                    test_array = test_string.split(" ");
                    first_word = test_array[0];
    }
}
}
first = new First();
first.Iterate();

I run PHP with PHP-CLI 5.3.10 and the Javascript with node v0.6.12.

For PHP I use 'memory_get_usage()' and for Javascript I use 'process.memoryUsage()'. I run them at the start of the script, then at the end, then minus end with start and finally convert the number of bytes into mb.

The PHP uses 0.00065 mb of memory whereas Javascript uses 0.25 mb however PHP takes 4 secs and Javascript takes 0.71 secs. I have run the results on 2 different machines.

Does anybody know why the Javascript memory usage would be so much higher than the PHP's (despite the fact that the Javascript is executed so much faster)?

The only explanation I could come up with was the V8's nature to use Hidden classes improves speed but increases memory consumption.

like image 599
Craig Taub Avatar asked Jan 14 '13 14:01

Craig Taub


1 Answers

Because they are very different execution environments.

In the case of PHP, the source is converted into a series of opcodes - kind of like p-code, while v8 uses a JIT compiler. The latter will tend to be more profilgate with memory usage, however I suspect the biggest difference between the 2 for memory usage is due to different policies for garbage collection:

$test_array = split(" ", $test_string);

and

test_array = test_string.split(" ");

create an object on the stack which is discarded at the end of each iteration.

Neither provide much access to controlling run time memory usage.

like image 140
symcbean Avatar answered Sep 19 '22 15:09

symcbean