Home  >  Article  >  Backend Development  >  Convert string to integer (int) intval() printf() performance test in PHP_PHP tutorial

Convert string to integer (int) intval() printf() performance test in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:20:31806browse

Background and Overview
As early as a few years before Sql injection became rampant, converting strings into integers was already listed as a necessary operation for every web program. The web program forces the id, integer and other values ​​​​from get or post to be converted into integers through the conversion function, filtering out dangerous characters and minimizing the possibility of the system itself being injected by Sql.
Nowadays, although Sql injection has gradually faded out of the stage of history, in order to ensure the normal operation of web programs, reduce the probability of errors, and better ensure user satisfaction, we also need to convert incorrect input from users into our required.
Conversion methods
In PHP, we can use 3 methods to convert strings into integers.
1. Forced type conversion method
Forced type conversion method is to "add the target type enclosed in parentheses before the variable to be converted" (extracted from the "Type Tricks" section of the PHP manual ) way.

Copy code The code is as follows:

$foo = "1"; // $foo Is a string type
$bar = (int)$foo; // $bar is an integer type
?>

 For integer type, the cast type name is int Or integer.
2. Built-in function method
The built-in function method uses PHP’s built-in function intval to convert variables.
Copy code The code is as follows:

$foo = "1"; // $foo Is a string type
$bar = intval($foo); // $bar is an integer type
?>

 The format of the intval function is:
 int intval(mixed $var [, int $base]); (Excerpted from the PHP manual)
Although the PHP manual clearly states that intval() cannot be used for conversion of array and object. But after my testing, there will be no problems when converting the array. The converted value is 1, not 0 as expected. I'm afraid it's because within PHP, array type variables are also considered to have non-zero values. When converting object, PHP will give the following notice:
 Object of class xxxx could not be converted to int in xxxxx.php on line xx
 The conversion value is also 1.
3. Format string method
The format string method is to use sprintf's %d to format the specified variable to achieve the purpose of type conversion.
Copy code The code is as follows:

$foo = "1"; // $foo Is a string type
$bar = sprintf("%d", $foo); // $bar is a string type
?>

Strictly speaking, sprintf The conversion result is still of string type, so it should not be regarded as a way to convert a string into an integer. But the string value after his processing has indeed become "an integer that is forced to be converted to a string type."
Actual test
The above introduces 3 ways to convert strings into integers in PHP. For ordinary programmers, this is the end. The following part is for abnormal programmers.
1. Basic function test
Set the following array:
Copy the code The code is as follows:

$a[] = "1";
$a[] = "a1";
$a[] = "1a";
$a[ ] = "1a2";
$a[] = "0";
$a[] = array('4',2);
$a[] = "2.3";
$a[] ​​= "-1";
$a[] = new Directory();
?>

Use three methods to convert the array given above in sequence elements to check the conversion status. The program source code is as follows:
Copy code The code is as follows:

$a[] = " 1";
$a[] = "a1";
$a[] = "1a";
$a[] = "1a2";
$a[] = "0" ;
$a[] = array('4',2);
$a[] = "2.3";
$a[] = "-1";
$a[] = new Directory();
// int
print "(int)
";
foreach($a as $v)
{
var_dump((int )$v);
print "
";
}
// intval
print "intval();
";
foreach( $a as $v)
{
var_dump(intval($v));
print "
";
}
// sprintf
print " sprintf();
";
foreach($a as $v)
{
var_dump(sprintf("%d", $v));
print "< ;br />";
}
?>

The final running result of the program is as follows (the notice that appears when converting object has been removed):
(int)
int(1)
int(0)
int(1)
int(1)
int(0)
int(1)
int(2)
int(-1)
int(1)
intval();
int(1)
int(0)
int(1)
int(1)
int(0)
int(1)
int(2)
int (-1)
int(1)
sprintf();
string(1) "1"
string(1) "0"
string(1) "1"
string(1) "1"
string(1) "0"
string(1) "1"
string(1) "2"
string(2) "-1"
string(1) "1"
  It can be seen that the results of the three conversions are exactly the same. So from a functional point of view, all three methods are capable of conversion work, so the next step is to see which one is more efficient.
2. Performance test
The tested string is one that we may use in injection work:
Copy code The code is as follows:

$foo = "1';Select * ...";
?>
Get the time point The function is as follows (used to obtain the test start point and end point to calculate the consumption time):

**
* Simple function to replicate PHP 5 behavior
*/
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec) ;
}
?>

  (Excerpted from the microtime() function section of the PHP manual)
The test process is to use each method to convert the variable $foo 1000000 times (1 million times ), and output their respective consumption times, and conduct a total of three sets of tests to reduce the error as much as possible. The test program is as follows:
Copy code The code is as follows:

function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$foo = "1';Select * ...";

// (int)
$fStart = microtime_float();
for($i=0;$i<1000000;$i++ )
{
$bar = (int)$foo;
}
$fEnd = microtime_float();
print "(int):" . ($fEnd - $fStart) . "s
";
// intval()
$fStart = microtime_float();
for($i=0;$i<1000000;$i++)
{
$bar = intval($foo);
}
$fEnd = microtime_float();
print "intval():" . ($fEnd - $fStart) . "s
// sprintf()
$fStart = microtime_float();
for($i=0;$i<1000000;$i++)
{
$bar = sprintf ("%d", $foo);
}
$fEnd = microtime_float();
print "sprintf():" . ($fEnd - $fStart) . "s
“; 🎜>(int):0.66051411628723s
intval():1.1493890285492s
sprintf():2.1008238792419s
(int):0.66878795623779s
intval():1.1 613430976868s
sprintf() :2.0976209640503s

Although this test is a bit abnormal (who would convert integers 1 million times in a row? ), but it can be seen that using cast to convert a string into an integer is the fastest.
Summary
Using forced type conversion to convert a string into an integer is one of the most direct conversion methods (you can directly obtain the integer variable value). From the perspective of code readability, the sprintf method code is relatively long, and the result may require forced type conversion again. The intval function is a typical process-oriented conversion, and forced type conversion is more direct. The idea of ​​"transformation" is conveyed to readers. In terms of efficiency, forced type conversion is also the fastest conversion method. Therefore, I recommend this method for programmers who often do conversion work.



http://www.bkjia.com/PHPjc/325067.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/325067.html

Background and Overview As early as a few years before Sql injection became rampant, converting strings into integers has been listed as a per- A necessary operation for a web program. The web program will force the id, integer and other values ​​​​from get or post...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn