Created
November 12, 2015 03:53
-
-
Save oanhnn/bddebdccb100b337200a to your computer and use it in GitHub Desktop.
Test performance of three determine content type methods
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 | |
class A | |
{ | |
protected $knownTypes = [ | |
'application/json' => true, | |
'application/xml' => true, | |
'text/xml' => true, | |
'text/html' => true, | |
]; | |
protected $keys; | |
protected $accept; | |
public function __construct($acceptHeader = '') | |
{ | |
$this->accept = $acceptHeader; | |
$this->keys = array_keys($this->knownTypes); | |
} | |
public function methodOne() | |
{ | |
$selectedContentTypes = array_intersect(explode(',', $this->accept), $this->keys); | |
if (count($selectedContentTypes)) { | |
return $selectedContentTypes[0]; | |
} | |
return 'text/html'; | |
} | |
public function methodTwo() | |
{ | |
foreach (explode(',', $this->accept) as $accept) { | |
if (in_array($accept, $this->keys)) { | |
return $accept; | |
} | |
} | |
return 'text/html'; | |
} | |
public function methodThree() | |
{ | |
foreach (explode(',', $this->accept) as $accept) { | |
if (isset($this->knownTypes[$accept])) { | |
return $accept; | |
} | |
} | |
return 'text/html'; | |
} | |
} | |
$a = new A('text/json,text/html,*/*'); | |
$start = microtime(true); | |
echo $a->methodOne() . PHP_EOL; | |
$one = microtime(true); | |
echo $a->methodTwo() . PHP_EOL; | |
$two = microtime(true); | |
echo $a->methodThree() . PHP_EOL; | |
$three = microtime(true); | |
printf("one: %f\ntwo: %f\nthree: %f", $one - $start, $two - $one, $three - $two); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment