Oct 5 2011
Unscientific Benchmarking of Type Casting, is_numeric, and regex in PHP
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"; |
Reducing Code using CodeIgniters Active Record Class Inheritance in CodeIgniter: Adding More Functionality To Your Models

