From 3d37a88f0b5e0696df8b410f4ab2a86cae0df177 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 18 Aug 2014 05:00:16 -0700 Subject: [PATCH] Replace is_object/is_array with switch on gettype When checking multiple types, this is ~10% slower in the worst case, and ~30-33% faster for the average and best case. See #218 --- src/Mustache/Context.php | 31 +++++++++++++++++++------------ src/Mustache/Template.php | 27 +++++++++++++++------------ 2 files changed, 34 insertions(+), 24 deletions(-) diff --git a/src/Mustache/Context.php b/src/Mustache/Context.php index 0115ff0..b87c99c 100644 --- a/src/Mustache/Context.php +++ b/src/Mustache/Context.php @@ -172,19 +172,26 @@ class Mustache_Context private function findVariableInStack($id, array $stack) { for ($i = count($stack) - 1; $i >= 0; $i--) { - if (is_object($stack[$i]) && !($stack[$i] instanceof Closure)) { + switch (gettype($stack[$i])) { + case 'object': + if (!($stack[$i] instanceof Closure)) { + // Note that is_callable() *will not work here* + // See https://github.com/bobthecow/mustache.php/wiki/Magic-Methods + if (method_exists($stack[$i], $id)) { + return $stack[$i]->$id(); + } elseif (isset($stack[$i]->$id)) { + return $stack[$i]->$id; + } elseif ($stack[$i] instanceof ArrayAccess && isset($stack[$i][$id])) { + return $stack[$i][$id]; + } + } + break; - // Note that is_callable() *will not work here* - // See https://github.com/bobthecow/mustache.php/wiki/Magic-Methods - if (method_exists($stack[$i], $id)) { - return $stack[$i]->$id(); - } elseif (isset($stack[$i]->$id)) { - return $stack[$i]->$id; - } elseif ($stack[$i] instanceof ArrayAccess && isset($stack[$i][$id])) { - return $stack[$i][$id]; - } - } elseif (is_array($stack[$i]) && array_key_exists($id, $stack[$i])) { - return $stack[$i][$id]; + case 'array': + if (array_key_exists($id, $stack[$i])) { + return $stack[$i][$id]; + } + break; } } diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index 4d1273d..f6e5f2e 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -113,19 +113,22 @@ abstract class Mustache_Template */ protected function isIterable($value) { - if (is_object($value)) { - return $value instanceof Traversable; - } elseif (is_array($value)) { - $i = 0; - foreach ($value as $k => $v) { - if ($k !== $i++) { - return false; - } - } + switch (gettype($value)) { + case 'object': + return $value instanceof Traversable; - return true; - } else { - return false; + case 'array': + $i = 0; + foreach ($value as $k => $v) { + if ($k !== $i++) { + return false; + } + } + + return true; + + default: + return false; } }