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

Fastest way to convert string to integer in PHP(在 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 中将字符串转换为整数的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Difference between mt_rand() and rand()(mt_rand() 和 rand() 的区别)
Coalesce function for PHP?(PHP的合并函数?)
2 Column Mysql Date Range Search in PHP(PHP中的2列Mysql日期范围搜索)
mysql match against ~ example(mysql 匹配 ~ 示例)
How-to: Ranking Search Results(操作方法:对搜索结果进行排名)
How to generate the snippet like those generated by Google with PHP and MySQL?(如何生成类似于 Google 使用 PHP 和 MySQL 生成的代码段?)