Created
July 6, 2011 11:51
-
-
Save ahwayakchih/1067053 to your computer and use it in GitHub Desktop.
Test PHP `DateTime(date())` vs `if(can call DateTime->setTimestamp) DateTime->setTimestamp() else DateTime(date())`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Test how calling `DateTime(date())` compares to checking for `DateTime::createFromFormat()` | |
* or `DateTime->setTimestamp()` and using `date()` as fallback only. | |
* | |
* Output should show something like: | |
* | |
* Using date() without any check: 4.3791408538818s | |
* Using DateTime::createFromFormat(): 5.6960089206696s | |
* Using DateTime->setTimestamp(): 3.3501291275024s | |
* | |
*/ | |
$string = time(); | |
// Benchmark code without function check | |
$start = microtime(true); | |
for ($i = 100000; $i > 0; $i--) { | |
if (is_numeric($string)) { | |
$date = new DateTime(date(DateTime::ISO8601, $string)); | |
} | |
} | |
$end = microtime(true) - $start; | |
echo "Using date() without any check: {$end}s\n"; | |
// Benchmark code that checks if method exists | |
$start = microtime(true); | |
for ($i = 100000; $i > 0; $i--) { | |
if(is_numeric($string)) { | |
if (method_exists('DateTime', 'createFromFormat')) { | |
$date = DateTime::createFromFormat('U', $string); | |
} | |
else { | |
$date = new DateTime(date(DateTime::ISO8601, $string)); | |
} | |
} | |
} | |
$end = microtime(true) - $start; | |
echo "Using DateTime::createFromFormat(): {$end}s\n"; | |
// Benchmark code that checks if method exists | |
$start = microtime(true); | |
for ($i = 100000; $i > 0; $i--) { | |
if(is_numeric($string)) { | |
if (method_exists('DateTime', 'setTimestamp')) { | |
$date = new DateTime(); | |
$date->setTimestamp($string); | |
} | |
else { | |
$date = new DateTime(date(DateTime::ISO8601, $string)); | |
} | |
} | |
} | |
$end = microtime(true) - $start; | |
echo "Using DateTime->setTimestamp(): {$end}s\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment