在PHP中使用较少的变量是否与性能有关?(Does using less variables matter performance wise in PHP?)

编程入门 行业动态 更新时间:2024-10-26 11:12:59
在PHP中使用较少的变量是否与性能有关?(Does using less variables matter performance wise in PHP?)

这两者之间是否有性能/资源差异?

$a = "foo bar"; $b = substr($a,-3); if ($b == "bar") { echo "bar!!"; }

if (substr($a = "foo bar", -3) == "bar") { echo "bar!!"; }

在第一个你正在使用一个额外的变量,我总是这样做是为了使它更具可读性,并且还可以在调试时知道值,我不喜欢在我的条件下进行任何处理,这真的很重要表现明智吗? 我使用更多记忆吗?

我想看看这两者在理论和实践上有何不同,是否应避免使用不必要的变量赋值?

Is there a performance/resources difference between these two?

$a = "foo bar"; $b = substr($a,-3); if ($b == "bar") { echo "bar!!"; }

and

if (substr($a = "foo bar", -3) == "bar") { echo "bar!!"; }

In the first one you are using an extra variable, I always do this for making it more readable, and also making it possible to know the value when debugging, I don't like to do any processing in my conditions, does this really matter performance wise? am I using more memory?

I'd like to see how these two differ theoretically and practically, should one avoid using unecessary variable assignments?

最满意答案

唯一的区别(除了AST和/或字节码的差异)是当你执行$b = substr($a, -3) ,你将返回的字符串保留在$b直到$b超出范围,然后释放引用,然后可以对字符串进行垃圾回收。

当你以另一种方式执行时,字符串用于比较"bar" ,然后立即丢弃,以便垃圾收集器可以更快地清理它。

这会对你产生影响吗? 不,不要把它考虑在内,因为它不能夸大它是多么小。 代码清晰。

The only difference (besides a difference in the AST and/or bytecode) is that when you do $b = substr($a, -3), you keep the returned string in $b until $b goes out of scope, then the reference is released and the string can then be garbage collected.

When you do it the the other way, the string is used in the comparison to "bar" and then is immediately discarded so the garbage collector can clean it up sooner.

Will this make a difference to you? No. Don't take it into account because it can't be overstated how small a thing it is. Code for clarity.

更多推荐

本文发布于:2023-07-05 06:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034342.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:较少   变量   性能   PHP   wise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!