Index: includes/entity.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/entity.inc,v
retrieving revision 1.4
diff -u -p -r1.4 entity.inc
--- includes/entity.inc	8 Dec 2009 06:33:11 -0000	1.4
+++ includes/entity.inc	3 Mar 2010 14:13:29 -0000
@@ -135,13 +135,6 @@ class DrupalDefaultEntityController impl
       $entities += $queried_entities;
     }
 
-    if ($this->cache) {
-      // Add entities to the cache if we are not loading a revision.
-      if (!empty($queried_entities) && !$this->revisionId) {
-        $this->cacheSet($queried_entities);
-      }
-    }
-
     // Ensure that the returned array is ordered the same as the original
     // $ids array if this was passed in and remove any invalid ids.
     if ($passed_ids) {
@@ -152,6 +145,13 @@ class DrupalDefaultEntityController impl
       }
       $entities = $passed_ids;
     }
+    if ($this->cache) {
+      // Add entities to the cache if we are not loading a revision.
+      if (!empty($queried_entities) && !$this->revisionId) {
+        $this->cacheSet($queried_entities);
+      }
+    }
+
 
     return $entities;
   }
@@ -295,6 +295,11 @@ class DrupalDefaultEntityController impl
    * Store entities in the static entity cache.
    */
   protected function cacheSet($entities) {
-    $this->entityCache += $entities;
+    $this->entityCache = $entities + $this->entityCache;
+    // Check if the cache is greater than the max cache size and purge
+    // the nodes at the bottom of the array as they are the least used.
+    if (count($this->entityCache) > variable_get('entity_max_cache', 100)) {
+      $this->entityCache = array_slice($this->entityCache, 0, variable_get($this->entityType . 'entity_max_cache', 100), TRUE);
+    }
   }
 }
