这两者之间是否有性能/资源差异?
$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.
更多推荐
发布评论