FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Last element in an array?
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Last element in an array? [message #169471 is a reply to message #169457] Tue, 14 September 2010 18:46 Go to previous messageGo to previous message
Thomas Mlynarczyk is currently offline  Thomas Mlynarczyk
Messages: 131
Registered: September 2010
Karma:
Senior Member
matt schrieb:

> $a = array(str_repeat("A", 10000));
> echo memory_get_usage() . "\n";
> $b = $a; // a full copy of a has NOT been made yet
> echo memory_get_usage() . "\n";
> $b[] = "B"; // now it has, I believe
> echo memory_get_usage() . "\n";

[outputs]
> 328436
> 328504
> 328752

> I would have expected the third number to be almost double the first
> based on my understanding. If PHP were making a copy right at the
> assignment operator, then I'd expect to see the 2nd and 3rd be double
> the first.

No. First, you should prepend a $before = memory_get_usage() to your
above code and then subtract $before from the three echoed values to
measure only what you intend to measure. On my system, that gives:

10248
10296
10488

As Marious explained, PHP doesn't actually create a copy unless it
really has to. So when you do $b = $a, no copy is made and both
variables point to the same value stored in memory. Only when you change
$b, the value is actually copied and the change performed on the copy.
But in your example above, you are not changing the 10000 chars string!
When you create the array $a, its first element will simply point to a
location in memory where the long string is stored. Now, when you do the
$b[] = "B", you are simply appending another string to the array, but
you leave its first element -- the long string -- unchanged. If you did
$b[0][0] = "B", then you would observe the expected memory consumption,
because you would change the long string's first character (and thereby
the whole string), so it would have to be copied:

10248
10296
20456

Greetings,
Thomas


--
Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche)
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Something I have never seen before
Next Topic: getting amount of deleted rows from: $result=odbc_exec($conn, 'delete from....');
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Mon Oct 21 03:21:43 GMT 2024

Total time taken to generate the page: 0.04150 seconds