Permalink
Browse files

BUGFIX Improved ClassInfo::ancestry() performance through in-memory c…

…aching and removal of unnecessary is_object() check - get_class() will complain if its not passed an object already)
  • Loading branch information...
chillu committed Jan 2, 2012
1 parent 72694d8 commit 4056b94f750cb088ca1ddf9f51bf3fe61738baef
Showing with 19 additions and 18 deletions.
  1. +19 −15 core/ClassInfo.php
  2. +0 −3 tests/core/ClassInfoTest.php
View
@@ -26,6 +26,11 @@ static function exists($class) {
* Cache for {@link hasTable()}
*/
private static $_cache_all_tables = null;
+
+ /**
+ * @var Array Cache for {@link ancestry()}.
+ */
+ private static $_cache_ancestry = array();
/**
* @todo Move this to SS_Database or DB
@@ -46,6 +51,7 @@ static function hasTable($class) {
static function reset_db_cache() {
self::$_cache_all_tables = null;
+ self::$_cache_ancestry = array();
}
/**
@@ -143,23 +149,21 @@ public static function subclassesFor($class) {
* @return array
*/
public static function ancestry($class, $tablesOnly = false) {
- $ancestry = array();
-
- if (is_object($class)) {
- $class = get_class($class);
- } elseif (!is_string($class)) {
- throw new InvalidArgumentException(sprintf(
- 'Invalid class value %s, must be an object or string', var_export($class, true)
- ));
+ if (!is_string($class)) $class = get_class($class);
+
+ $cacheKey = $class . '_' . (string)$tablesOnly;
+ $parent = $class;
+ if(!isset(self::$_cache_ancestry[$cacheKey])) {
+ $ancestry = array();
+ do {
+ if (!$tablesOnly || DataObject::has_own_table($parent)) {
+ $ancestry[$parent] = $parent;
+ }
+ } while ($parent = get_parent_class($parent));
+ self::$_cache_ancestry[$cacheKey] = array_reverse($ancestry);
}
- do {
- if (!$tablesOnly || DataObject::has_own_table($class)) {
- $ancestry[$class] = $class;
- }
- } while ($class = get_parent_class($class));
-
- return array_reverse($ancestry);
+ return self::$_cache_ancestry[$cacheKey];
}
/**
@@ -70,9 +70,6 @@ public function testAncestry() {
$this->assertEquals(array('ClassInfoTest_BaseClass' => 'ClassInfoTest_BaseClass'), $ancestry,
'$tablesOnly option excludes memory-only inheritance classes'
);
-
- $this->setExpectedException('InvalidArgumentException');
- ClassInfo::ancestry(42);
}
/**

0 comments on commit 4056b94

Please sign in to comment.