Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does declaring an unnecessary variable in PHP consumes memory?

I usually do this in PHP for better readability but I don't know if it consumes memory or has any other issues? Let's say I have this code:

$user = getUser(); // getUser() will return an array

I could do:

$email = $user["email"];
sendEmail($email);

Without declaring the variable $email I could do:

sendEmail($user["email"]);

Which one is better? Consider that this is just a very simple example.

like image 749
Luis Elizondo Avatar asked Jan 25 '13 10:01

Luis Elizondo


1 Answers

Don't make your code less readable just to save a few bytes. And this will not save you more, even if $email is a 100 MB string, because internally PHP uses the copy on write mechanism: The content of a variable is not copied unless you change it.

Example:

$a = str_repeat('x', 100000000); // Memory used ~ 100 MB
$b = $a;                         // Memory used ~ 100 MB
$b = $b . 'x';                   // Memory used ~ 200 MB
like image 119
Fabian Schmengler Avatar answered Sep 28 '22 18:09

Fabian Schmengler