Fastest way to convert string to integer in PHP(在 PHP 中将字符串转换为整数的最快方法)
问题描述
使用 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 测试
这篇关于在 PHP 中将字符串转换为整数的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 中将字符串转换为整数的最快方法
基础教程推荐
- php中的PDF导出 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- php中的foreach复选框POST 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
