问题描述
使用 PHP,将这样的字符串转换为整数的最快方法是什么:"123"?
Using PHP, what's the fastest way to convert a string like this: "123" to an integer?
为什么那个特定的方法是最快的?如果它收到意外的输入,例如 "hello" 或数组,会发生什么?
Why is that particular method the fastest? What happens if it gets unexpected input, such as "hello" or an array?
推荐答案
我刚刚设置了一个快速的基准测试练习:
I've just set up a quick benchmarking exercise:
Function time to run 1 million iterations -------------------------------------------- (int) "123": 0.55029 intval("123"): 1.0115 (183%) (int) "0": 0.42461 intval("0"): 0.95683 (225%) (int) int: 0.1502 intval(int): 0.65716 (438%) (int) array("a", "b"): 0.91264 intval(array("a", "b")): 1.47681 (162%) (int) "hello": 0.42208 intval("hello"): 0.93678 (222%)
平均而言,调用 intval() 慢两倍半,如果您的输入已经是整数,则差异最大.
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
我很想知道为什么.
更新:我再次运行测试,这次使用强制(0 + $var)
Update: I've run the tests again, this time with coercion (0 + $var)
| INPUT ($x) | (int) $x |intval($x) | 0 + $x | |-----------------|------------|-----------|-----------| | "123" | 0.51541 | 0.96924 | 0.33828 | | "0" | 0.42723 | 0.97418 | 0.31353 | | 123 | 0.15011 | 0.61690 | 0.15452 | | array("a", "b") | 0.8893 | 1.45109 | err! | | "hello" | 0.42618 | 0.88803 | 0.1691 | |-----------------|------------|-----------|-----------|
附录:我刚刚遇到了一个稍微出乎意料的行为,您在选择其中一种方法时应该注意:
Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
$x = "11"; (int) $x; // int(11) intval($x); // int(11) $x + 0; // int(11) $x = "0x11"; (int) $x; // int(0) intval($x); // int(0) $x + 0; // int(17) ! $x = "011"; (int) $x; // int(11) intval($x); // int(11) $x + 0; // int(11) (not 9)
使用 PHP 5.3.1 测试