Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange memory usage in while(1) vs. for(;;)

I have the 2 following codes.

1:

$i = 0;
while(1)
{
    $i++;

    echo "big text for memory usage ";
    if ( $i == 50000 )
    break;
}

echo "<br />" . memory_get_usage();

It echoes every time : 1626464

2:

$i = 0;
for(;;)
{
    $i++;

    echo "big text for memory usage ";
    if ( $i == 50000 )
    break;
}

echo "<br />" . memory_get_usage();

It echoes every time : 1626656

Can anybody exaplain this difference between the 2 different memory usages? Even if they are so small...

like image 828
Cosmin Avatar asked Jul 06 '26 03:07

Cosmin


1 Answers

It's an implementation detail. With the for loop, PHP probably uses some space to store three pointers, one for the for intialization, one for the incrementation, and one for the stop condition. If you're on a 64-bit system, then this accounts for the 64 * 3 = 192 extra bits you're seeing. Of course, it's hard to tell if I'm right without looking at the actual code.

like image 104
Quentin Pradet Avatar answered Jul 08 '26 16:07

Quentin Pradet