在 PHP 中声明一个不必要的变量会消耗内存吗? [英] Does declaring an unnecessary variable in PHP consumes memory?
问题描述
我通常在 PHP 中执行此操作以获得更好的可读性,但我不知道它是否消耗内存或有任何其他问题?假设我有这个代码:
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
我可以做到:
$email = $user["email"];
sendEmail($email);
不声明变量 $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.
推荐答案
不要为了节省几个字节而降低代码的可读性.即使 $email
是一个 100 MB 的字符串,这也不会为您节省更多,因为 PHP 在内部使用了写入时复制机制:内容 除非您更改变量,否则不会复制它.
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.
示例:
$a = str_repeat('x', 100000000); // Memory used ~ 100 MB
$b = $a; // Memory used ~ 100 MB
$b = $b . 'x'; // Memory used ~ 200 MB
这篇关于在 PHP 中声明一个不必要的变量会消耗内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!