PHP converts a string to an integer (int) intval () printf () Performance test _php Tips

Source: Internet
Author: User
Tags explode sprintf sql injection
Background, overview
As early as the SQL injection rampage, the string converted to integers has been listed as a prerequisite for every Web application. The Web program converts the ID, integer equivalent of Get or post to an integer, filters out dangerous characters, and reduces the likelihood of the system itself being injected by SQL.
Now, although the SQL injection has gradually faded out of the historical arena, but in order to ensure the normal operation of the Web program, reduce the error probability, better guarantee the use of satisfaction, we also need to put the user's incorrect input into what we need.
Transformation mode
In PHP, we can convert a string to an integer in 3 different ways.
1. Coercion Type conversion method
The way to force type conversions is to "precede the variable to be converted with the target type enclosed in parentheses" (excerpt from the PHP manual "type trick" section).
Copy Code code as follows:

<?php
$foo = "1"; $foo is a String type
$bar = (int) $foo; $bar is an integral type
?>

For integral types, the cast type name is int or integer.
2. Built-in function mode
The built-in function approach is to use PHP's built-in function intval for variable conversion operations.
Copy Code code as follows:

<?php
$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 it is clearly stated in the PHP Manual, Intval () cannot be used for the conversion of array and object. But after my test, the conversion array does not have any problems, the conversion value is 1, rather than the imaginary 0. I'm afraid it's because inside PHP, the array-type variables are also considered to be 0 worthwhile. When converting object, PHP gives the following notice:
Object of class xxxx could not is converted to int into xxxxx.php on line xx
The conversion value is also 1.
3. Format string Method
The format string is used to format the specified variable with sprintf%d to achieve the purpose of the type conversion.
Copy Code code as follows:

<?php
$foo = "1"; $foo is a String type
$bar = sprintf ("%d", $foo); $bar is a String type
?>

Strictly speaking, the result of a sprintf conversion is a string, 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 coerced into a string type."
Actual test
The above describes 3 ways to convert strings to integers in PHP. For a typical programmer, seeing this is the end of the list, the following sections are for the sick programmer.
1. Basic function test
Set the following array:
Copy Code code as follows:

<?php
$a [] = "1";
$a [] = "A1";
$a [] = "1a";
$a [] = "1a2";
$a [] = "0";
$a [] = Array (' 4 ', 2);
$a [] = "2.3";
$a [] = "-1";
$a [] = new Directory ();
?>

Use three ways to turn the elements in the array given above to see the conversion. The program source code is as follows:
Copy Code code as follows:

<?php
$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) <br/>";
foreach ($a as $v)
{
Var_dump ((int) $v);
print "<br/>";
}
Intval
Print "intval (); <br/>";
foreach ($a as $v)
{
Var_dump (Intval ($v));
print "<br/>";
}
sprintf
Print "sprintf (); <br/>";
foreach ($a as $v)
{
Var_dump (sprintf ("%d", $v));
print "<br/>";
}
?>

The results of the program's final run are 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"
From this we can see that the results of the three conversions are exactly the same. So from a functional perspective, 3 ways to do the conversion work, then the next job is to see which is more efficient.
2. Performance Test
The string being tested is one we might use in the injection effort:
Copy Code code as follows:

<?php
$foo = "1"; SELECT * ... ";
?>
The function to get the point in time is as follows (used to get the test starting point and end point to calculate the time consumed):

<?php
**
* 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) in each way, and the respective consumption time output, a total of three sets of tests, as far as possible to reduce the error. The test procedure is as follows:
Copy Code code as follows:

<?php
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<br/>";
Intval ()
$fStart = Microtime_float ();
For ($i =0 $i <1000000; $i + +)
{
$bar = Intval ($foo);
}
$fEnd = Microtime_float ();
Print "Intval ():". ($fEnd-$fStart). "S<br/>";
sprintf ()
$fStart = Microtime_float ();
For ($i =0 $i <1000000; $i + +)
{
$bar = sprintf ("%d", $foo);
}
$fEnd = Microtime_float ();
Print "sprintf ():". ($fEnd-$fStart). "S<br/>";
?>

Final Test results:
(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 integers for 100w consecutive times?) , but you can see that using coercion type conversions is the fastest time to convert a string to an integer speed.
Summarize
Converting a string to an integer using coercion type conversion is one of the most direct transformations (you can get the variable value of an integral type directly). From the point of view of the code readability, the sprintf mode code is long, and the result may need to be forced type conversion again, while the Intval function is a typical process-oriented conversion, forcing type conversion is more direct to pass the thought "I want to transform" to the reader. In terms of efficiency, forced type conversion is also the fastest way to transform. As a result, I recommend this approach for programmers who are often working on transformations.

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.