PHP switch 语句 VS if elseif 语句基准

PHP switch statement VS if elseif statement benchmark

我检查这个 PHP website benchmark 以检查 switch statement VS if else if statement。我看到了这个结果:

switch 和 if 结构之间有区别吗?调用 1'000x

结果我看到 if else if 更快 (+ **100 %** *if, elseif and else (using ===)* Total time: 117 µsview code)。

这个基准是正确的,if, elseif and else (using ===) 比 switch 语句更好更快?!

是否会得到完全相同的结果取决于您正在评估的条件、您的设备、设置和其他因素。但是,是的,通常 if/elseif/else 严格比较 (===) 会优于 switch。原因是switch uses "loose" (i.e., type-insensitive) comparison (==),它比类型敏感比较(===)慢。

请记住,这些差异非常小,如果您的算法效率低下,这些差异将相形见绌。因此,只有在确定已消除其他主要瓶颈后,您才应调整此类细节。

默认 PHP 开关不完全匹配。

exact match switch 的一些示例。