gpt4 book ai didi

php - 在 PHP 中将字符串转换为整数的最快方法

转载 作者:IT老高 更新时间:2023-10-28 11:38:35 26 4
gpt4 key购买 nike

使用 PHP,将这样的字符串 "123" 转换为整数的最快方法是什么?

为什么这种特定方法最快?如果收到意外输入,例如 "hello" 或数组会怎样?

最佳答案

我刚刚建立了一个快速的基准测试练习:

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() 会慢两倍半,如果您的输入已经是整数,则差异最大。

我很想知道为什么


更新:我再次运行测试,这次使用强制 (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 |
|-----------------|------------|-----------|-----------|

附录:我刚刚遇到了一个稍微出乎意料的行为,您在选择其中一种方法时应该注意:

$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 测试

关于php - 在 PHP 中将字符串转换为整数的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/239136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com