elseif与else if之间的根本区别 [英] underlying difference between elseif vs else if
问题描述
我想知道elseif
和else if
之间的区别.
I was wondering the differnce between elseif
and else if
.
我正在阅读手册,其中指出是否使用括号{}
它们的用法相同,但是不使用花括号时,只有elseif
起作用.
I was reading the manual which says if using the braces {}
they are treated the same but only elseif
works when not using the braces.
另一位贡献者说:
请注意} elseif(){比} else if(){
Note that } elseif() { is somewhat faster than } else if() {
他用基准测试对其进行了备份.
and he backed it up with a benchmark test.
在我看来,elseif是说它和说:的真正方法.
To me it seems like elseif is the true way of saying it and saying:
else if() {...}
确实等同于:
else { if() {...} }
这可能解释了为什么它稍微慢一些.
which might explain why its marginally slower.
我习惯使用else if
,因为那也是我用其他语言编写的方式.我真的不认为键入哪种方式很重要(除非您不使用花括号..但我认为无论如何都使用花括号总是很好的),我只是对底层的细节感到好奇.
I am used to using else if
because thats how I do it in other languages as well. I don't really think it matters which way you type it (unless you are not using braces.. but I think its always good to use braces anyways) I was just curious about the underlying details.
我正确吗?
推荐答案
除了我的评论,从PHP源码中可以看到,唯一提高速度的是PHP的解析器为elseif
提供了特殊标记,毫不奇怪地称为T_ELSEIF
.但是我敢肯定,提高速度无非是在替代语法中允许elseif
的副作用:
In addition to my comment, from what I can see in the PHP source, the only speed boost is that PHP's parser has a special token for elseif
, unsurprisingly known as T_ELSEIF
. But I'm sure the speed boost is nothing more than a side effect of allowing elseif
in the alternative syntax:
if (cond1):
// Do something
elseif (cond2):
// Do something else
else:
// Do something else
endif;
类似于Python,它使用elif
,else if
和空格,而不必不必要地使解析器的实现代码复杂化(即在看到冒号和if
关键字之间采取不同的动作).因此,分别在else
和if
之后分别需要一个冒号,这就是语言规则的规定.
Similar to Python, which uses elif
, else if
with a space wouldn't be allowed without having to unnecessarily complicate the parser's implementation code (i.e. to act differently between seeing a colon and the if
keyword). So a colon is required directly after else
and if
respectively, and that's how the language rule is stipulated.
Ergo,我很确定PHP会将else if
视为单语句else
中的条件块.
Ergo I'm pretty sure PHP just treats else if
as a conditional block in a singular-statement else
.
如果所有速度差异 ,都应将其归咎于解析器.
If there are any speed differences at all, blame the parser for most of them.
这篇关于elseif与else if之间的根本区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!