Convert string to Integer (int) intval () printf () in PHP performance Test _php Tutorial

Source: Internet
Author: User
Tags sprintf
Background, overview
As early as the first few years of SQL injection rampage, strings converted to integers have been listed as prerequisites for each Web application. The Web program converts a GET or post ID, an integer equivalent, into an integer, filters out dangerous characters, and minimizes the likelihood that the system itself will be injected into SQL.
Today, although SQL injection has gradually faded out of the historical stage, but in order to ensure the normal operation of the Web program, reduce the probability of error, and better guarantee the satisfaction, we also need to translate the user's incorrect input into what we need.
Conversion Mode
In PHP, we can use 3 ways to convert a string to an integer.
1. Coercion Type conversion Mode
The way to force type conversions is to "precede the variables to be converted with the target type enclosed in parentheses" (excerpt from the PHP manual "type-trick" section).
Copy CodeThe code is as follows:
$foo = "1"; $foo is a String type
$bar = (int) $foo; $bar is an integral type
?>

For an integer type, the cast type name is int or integer.
2. Built-in function mode
The built-in function is to use PHP's built-in function intval to perform variable conversion operations.
Copy CodeThe code is as follows:
$foo = "1"; $foo is a String type
$bar = Intval ($foo); $bar is an integral type
?>

   the format of the Intval function is:
int intval (mixed $var [, int $base]); (Excerpt from PHP manual)
Although the PHP manual explicitly states that Intval () cannot be used for the conversion of array and object. But after I tested it, there was no problem with converting an array, with a value of 1 instead of 0. I'm afraid because inside PHP, a variable of type array is considered non-0 worth it. When you convert an object, PHP gives the following notice:
Object of class xxxx could not being converted to Int. xxxxx.php on line XX
The conversion value is also 1.
3. Formatting strings
Format the string by using sprintf%d to format the specified variable to achieve the purpose of type conversion.
Copy CodeThe code is as follows:
$foo = "1"; $foo is a String type
$bar = sprintf ("%d", $foo); $bar is a String type
?>

The sprintf is strictly a string type, so it should not be considered as a way to convert a string into an integer. But the string value after his processing has indeed become "an integer that is coerced into a string type."
Actual test
Here are 3 ways to convert a string to an integer in PHP. For the average programmer, seeing this is the end of the case, the following part is for the perverted programmer.
1. Basic function test
Set the following array:
Copy CodeThe 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 different ways to convert the elements in the array given above to see how the conversion is happening. The program source code is as follows:
Copy CodeThe 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 "
";
}
?>

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"
As you can see, the results of the three conversions are exactly the same. Then functionally speaking, 3 ways can be competent for conversion work, then the next task is to see which one is more efficient.
2. Performance Testing
The tested string is one that we might use in our injection work:
Copy CodeThe code is as follows:
$foo = "1"; SELECT * ... ";
?>
The function that gets the point in time is the following (used to get the test start and end points to calculate the consumption time):

**
* Simple function to replicate PHP 5 behaviour
*/
function Microtime_float ()
{
List ($usec, $sec) = Explode ("", Microtime ());
return (float) $usec + (float) $sec);
}
?>

(Excerpt from PHP manual Microtime () function section)
The test process is to convert the variable $foo 1 million times (1 million times) using each method, and output the respective consumption time in a total of three sets of tests to minimize the error. The test procedure is as follows:
Copy CodeThe 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
";
?>

The final Test result:
(int): 0.67205619812012s
Intval (): 1.1603000164032s
sprintf (): 2.1068270206451s
(int): 0.66051411628723s
Intval (): 1.1493890285492s
sprintf (): 2.1008238792419s
(int): 0.66878795623779s
Intval (): 1.1613430976868s
sprintf (): 2.0976209640503s

Although this test is a bit perverted (who will convert the whole number of 100w times in succession?) ), but it can be seen that converting a string to an integer speed using a forced type conversion is the fastest.
Summarize
Converting a string to an integer using a forced type conversion is one of the most straightforward conversions (you can get the variable value of an integral type directly). From the code readability point of view, the sprintf way code is long, and the results may also need to be forced to cast the type conversion, and the Intval function is a typical process-oriented conversion, forced type conversion is more straightforward to the "I want to transform" the idea of passing to the reader. In terms of efficiency, forced type conversion is also the fastest way to transform. Therefore, I recommend this approach for programmers who often work on conversions.

http://www.bkjia.com/PHPjc/325067.html www.bkjia.com true http://www.bkjia.com/PHPjc/325067.html techarticle background, overview as early as the previous years of SQL injection rampage, the string conversion to an integer has been listed as a prerequisite for each Web application. The Web program enforces get or post IDs, integer equivalents ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.