diff --git a/core/includes/theme.inc b/core/includes/theme.inc
index 62bbb58..3f459b5 100644
--- a/core/includes/theme.inc
+++ b/core/includes/theme.inc
@@ -119,7 +119,7 @@ function drupal_theme_rebuild() {
  */
 function drupal_find_theme_functions($cache, $prefixes) {
   $implementations = array();
-  $functions = get_defined_functions();
+  $grouped_functions = drupal_collect_prefix_grouped_functions();
 
   foreach ($cache as $hook => $info) {
     foreach ($prefixes as $prefix) {
@@ -135,8 +135,9 @@ function drupal_find_theme_functions($cache, $prefixes) {
       // are found using the base hook's pattern, not a pattern from an
       // intermediary suggestion.
       $pattern = isset($info['pattern']) ? $info['pattern'] : ($hook . '__');
-      if (!isset($info['base hook']) && !empty($pattern)) {
-        $matches = preg_grep('/^' . $prefix . '_' . $pattern . '/', $functions['user']);
+      // Grep only the functions functions which are within the prefix group.
+      if (!isset($info['base hook']) && !empty($pattern) && isset($grouped_functions[$prefix])) {
+        $matches = preg_grep('/^' . $prefix . '_' . $pattern . '/', $grouped_functions[$prefix]);
         if ($matches) {
           foreach ($matches as $match) {
             $new_hook = substr($match, strlen($prefix) + 1);
@@ -164,6 +165,34 @@ function drupal_find_theme_functions($cache, $prefixes) {
 }
 
 /**
+ * Collect all user functions grouped by possible prefixes.
+ *
+ * @return array
+ *   Functions grouped by possible prefixes.
+ */
+function drupal_collect_prefix_grouped_functions() {
+  $functions = get_defined_functions();
+
+  $grouped_functions = array();
+  foreach ($functions['user'] as $function) {
+    // Storing user defined functions keyed for fast function_exists lookups.
+    // Splitting user defined function into parts to group the functions by
+    // possible prefixes.
+    $parts = explode('_', $function);
+    $count = count($parts);
+    $prefix = '';
+    for ($i = 0; $i < $count; $i++) {
+      $prefix .= $parts[$i];
+      // Avoid grepping all possible user functions which match this prefix by
+      // storing the function name grouped into all its possible prefixes.
+      $grouped_functions[$prefix][] = $function;
+      $prefix .= '_';
+    }
+  }
+  return $grouped_functions;
+}
+
+/**
  * Allows themes and/or theme engines to easily discover overridden templates.
  *
  * @param $cache
