在PHP中将字符串转换为整数的最快方法 [英] Fastest way to convert string to integer in PHP

查看:200
本文介绍了在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.

我有兴趣了解为什么虽然。

更新:我已经运行测试,这次强制使用 $ 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)

sub>

Tested using PHP 5.3.1

这篇关于在PHP中将字符串转换为整数的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆