I performed some unscientific PHP benchmarks today pitting casting to an integer against is_numeric against preg_replace. The point was to see which is the fastest way of quickly cleaning user input before passing to a SQL query to prevent against SQL injection. Obviously this would only work on database fields that are integers. To be fair I should’ve benchmarked mysql_real_escape_string in the same way, but I’m sure its a loser in this test. The test is run in a for loop 100,000 times. None of the code being used here is very expensive to begin with — but here we go:
Casting to (INT)
0.017745018005371
Using is_numeric()
0.028823852539062
Using preg_replace()
0.087189197540283
$start = microtime(true); /*for($i=0;$i<100000;$i++){ $v = (INT) "$i"; }*/ /*for($i=0;$i<100000;$i++){ is_numeric("$i"); }*/ for($i=0;$i<100000;$i++){ preg_replace('/\D/','',"$i"); } $end = microtime(true); echo "\nTime: ".($end-$start)."\n";
Related posts:
- Type Casting In PHP To Prevent XSS and SQL Injection
- PHP Tertiary Statement – Using Tertiaries in PHP
- Optimize MySQL Queries – Fast Inserts With Multiple Rows
- Convert a PHP Object to an Array
- How To Write a Page Controller in PHP for Dynamic Content
Tags: benchmarking, int, is_numeric, mysql, php, php5, preg_replace, regex, type caste