Skip to content

Commit

Permalink
Optimizing some of the Hash functions by returning early.
Browse files Browse the repository at this point in the history
When no deep path is going to be used, it is 11% faster to just access
the property directly and operate on it.
  • Loading branch information
lorenzo committed May 17, 2014
1 parent b24e492 commit bfd2d78
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/Utility/Hash.php
Expand Up @@ -42,7 +42,14 @@ public static function get(array $data, $path, $default = null) {
if (empty($data)) {
return $default;
}
if (is_string($path) || is_numeric($path)) {

$isString = is_string($path);

if ($isString && strpos($path, '.') === false) {
return isset($data[$path]) ? $data[$path] : $default;
}

if ($isString || is_numeric($path)) {
$parts = explode('.', $path);
} else {
$parts = $path;
Expand Down Expand Up @@ -240,13 +247,19 @@ protected static function _matches(array $data, $selector) {
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::insert
*/
public static function insert(array $data, $path, $values = null) {
if (strpos($path, '[') === false) {
$noTokens = strpos($path, '[') === false;
if ($noTokens && strpos($path, '.') === false) {
$data[$path] = $values;
return $data;
}

if ($noTokens) {
$tokens = explode('.', $path);
} else {
$tokens = String::tokenize($path, '.', '[', ']');
}

if (strpos($path, '{') === false && strpos($path, '[') === false) {
if ($noTokens && strpos($path, '{') === false) {
return static::_simpleOp('insert', $data, $tokens, $values);
}

Expand Down Expand Up @@ -323,13 +336,17 @@ protected static function _simpleOp($op, $data, $path, $values = null) {
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::remove
*/
public static function remove(array $data, $path) {
if (strpos($path, '[') === false) {
$tokens = explode('.', $path);
} else {
$tokens = String::tokenize($path, '.', '[', ']');
$noTokens = strpos($path, '[') === false;
$noExpansion = strpos($path, '{') === false;

if ($noExpansion && $noTokens && strpos($path, '.') === false) {
unset($data[$path]);
return $data;
}

if (strpos($path, '{') === false && strpos($path, '[') === false) {
$tokens = $noTokens ? explode('.', $path) : String::tokenize($path, '.', '[', ']');

if ($noExpansion && $noTokens) {
return static::_simpleOp('remove', $data, $tokens);
}

Expand Down

0 comments on commit bfd2d78

Please sign in to comment.