Skip to content

Instantly share code, notes, and snippets.

@oanhnn
Created November 12, 2015 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oanhnn/bddebdccb100b337200a to your computer and use it in GitHub Desktop.
Save oanhnn/bddebdccb100b337200a to your computer and use it in GitHub Desktop.
Test performance of three determine content type methods
<?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