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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/239136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:02:03  来源:igfitidea点击:

Fastest way to convert string to integer in PHP

phpoptimizationcasting

提问by nickf

Using PHP, what's the fastest way to convert a string like this: "123"to an integer?

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

Why is that particular method the fastest? What happens if it gets unexpected input, such as "hello"or an array?

为什么那个特定的方法是最快的?如果它得到意外的输入,例如"hello"或 数组,会发生什么?

回答by nickf

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%)

On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.

平均而言,调用 intval() 慢两倍半,如果您的输入已经是整数,则差异最大。

I'd be interested to know whythough.

我很想知道为什么



Update: I've run the tests again, this time with coercion (0 + $var)

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

Tested using PHP 5.3.1

使用 PHP 5.3.1 测试

回答by Rexxars

I personally feel casting is the prettiest.

我个人觉得选角是最漂亮的。

$iSomeVar = (int) $sSomeOtherVar;

Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0.

如果发送像“Hello”这样的字符串,它将被转换为整数 0。对于像“22 岁”这样的字符串,它将被转换为整数 22。任何不能解析为数字的内容都将变为 0。

If you really do NEED the speed, I guess the other suggestions here are correct in assuming that coercion is the fastest.

如果你真的需要速度,我想这里的其他建议是正确的,假设强制是最快的。

回答by staticsan

Run a test.

运行测试。

   string coerce:          7.42296099663
   string cast:            8.05654597282
   string fail coerce:     7.14159703255
   string fail cast:       7.87444186211

This was a test that ran each scenario 10,000,000 times. :-)

这是一个测试,每个场景运行 10,000,000 次。:-)

Co-ercion is 0 + "123"

强制是 0 + "123"

Casting is (integer)"123"

铸造是 (integer)"123"

I think Co-ercion is a tiny bit faster. Oh, and trying 0 + array('123')is a fatal error in PHP. You might want your code to check the type of the supplied value.

我认为强制转换要快一点。哦,尝试0 + array('123')是 PHP 中的一个致命错误。您可能希望您的代码检查所提供值的类型。

My test code is below.

我的测试代码如下。



function test_string_coerce($s) {
    return 0 + $s;
}

function test_string_cast($s) {
    return (integer)$s;
}

$iter = 10000000;

print "-- running each text $iter times.\n";

// string co-erce
$string_coerce = new Timer;
$string_coerce->Start();

print "String Coerce test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('123');
}

$string_coerce->Stop();

// string cast
$string_cast = new Timer;
$string_cast->Start();

print "String Cast test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('123');
}

$string_cast->Stop();

// string co-erce fail.
$string_coerce_fail = new Timer;
$string_coerce_fail->Start();

print "String Coerce fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('hello');
}

$string_coerce_fail->Stop();

// string cast fail
$string_cast_fail = new Timer;
$string_cast_fail->Start();

print "String Cast fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('hello');
}

$string_cast_fail->Stop();

// -----------------
print "\n";
print "string coerce:          ".$string_coerce->Elapsed()."\n";
print "string cast:            ".$string_cast->Elapsed()."\n";
print "string fail coerce:     ".$string_coerce_fail->Elapsed()."\n";
print "string fail cast:       ".$string_cast_fail->Elapsed()."\n";


class Timer {
    var $ticking = null;
    var $started_at = false;
    var $elapsed = 0;

    function Timer() {
        $this->ticking = null;
    }

    function Start() {
        $this->ticking = true;
        $this->started_at = microtime(TRUE);
    }

    function Stop() {
        if( $this->ticking )
            $this->elapsed = microtime(TRUE) - $this->started_at;
        $this->ticking = false;
    }

    function Elapsed() {
        switch( $this->ticking ) {
            case true: return "Still Running";
            case false: return $this->elapsed;
            case null: return "Not Started";
        }
    }
}

回答by Nishchit Dhanani

You can simply convert long string into integer by using FLOAT

您可以使用 FLOAT 简单地将长字符串转换为整数

$float = (float)$num;

$float = (float)$num;

Or if you want integer not floating val then go with

或者,如果您想要整数而不是浮动 val,那么请使用

$float = (int)$num;

$float = (int)$num;

For ex.

例如。

(int)   "1212.3"   = 1212 
(float) "1212.3"   = 1212.3

回答by Developer

integer excract from any string

从任何字符串中提取整数

$in = 'tel.123-12-33';

$in = 'tel.123-12-33';

preg_match_all('!\d+!', $in, $matches);
$out =  (int)implode('', $matches[0]);

//$out ='1231233';

//$out ='1231233';

回答by Elric Wamugu

$int = settype("100", "integer"); //convert the numeric string to int

回答by Andrew Plank

Ran a benchmark, and it turns out the fastest way of getting a realinteger (using all the available methods) is

运行一个基准测试,结果证明获得一个数的最快方法(使用所有可用的方法)是

$foo = (int)+"12.345";

Just using

只是使用

$foo = +"12.345";

returns a float.

返回一个浮点数。

回答by Daniel

More ad-hoc benchmark results:

更多临时基准测试结果:

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = (integer) "-11";}'     

real    2m10.397s
user    2m10.220s
sys     0m0.025s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i += "-11";}'              

real    2m1.724s
user    2m1.635s
sys     0m0.009s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = + "-11";}'             

real    1m21.000s
user    1m20.964s
sys     0m0.007s