Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.

Posts Tagged ‘int’

Unscientific Benchmarking of Type Casting, is_numeric, and regex in PHP

Posted by chris on October 5th, 2011 Comments(0)

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";
In Programming (, , , , , , , , )