diff --git a/includes/flag/flag_comment.inc b/includes/flag/flag_comment.inc
index 7056023..4b70aed 100644
--- a/includes/flag/flag_comment.inc
+++ b/includes/flag/flag_comment.inc
@@ -69,6 +69,82 @@ class flag_comment extends flag_entity {
     return $comment->cid;
   }
 
+  /**
+   * Overrides flag_flag::get_flagging_record().
+   *
+   * This queries for flagging records for all comments on the node for the
+   * current comment, and prefills the flag_get_user_flags() static cache with
+   * the result for a performance gain.
+   */
+  function get_flagging_record($entity_id, $uid = NULL, $sid = NULL) {
+    static $seen_comment_nids = array();
+
+    $comment = $this->fetch_entity($entity_id);
+
+    // Figure out if this is the first comment we've seen for its parent node.
+    if (!isset($seen_comment_nids[$comment->nid])) {
+      // Preload the flag_get_user_flags() static cache with flagging records
+      // for all the comments on the node. This means that if multiple comments
+      // on this node are being viewed, only one query is run for all their
+      // flagging records, rather than one for each comment. This is because
+      // flag_get_user_flags() can only optimized across flags on one entity.
+      $flag_get_user_flags_cache = &drupal_static('flag_get_user_flags');
+
+      // We need to get a row for each comment, including empty ones if there is
+      // no flagging, so that the cache is warmed up for all comments. Therefore
+      // the query has to have the {comment} table as its base, and include the
+      // comment cid field.
+      $query = db_select('comment', 'c');
+      $query->leftJoin('flagging', 'f',
+        "c.cid = f.entity_id AND f.entity_type = 'comment'");
+      $query->fields('f')
+        ->fields('c', array('cid'))
+        ->condition('c.nid', $comment->nid)
+        ->condition(db_or()
+          // We want to include rows for comments which have no flaggings at all
+          // for the current user.
+          ->isNull('f.flagging_id')
+          // The same conditions as flag_get_user_flags()'s query.
+          ->condition(db_and()
+            ->condition(db_or()
+              ->condition('f.uid', $uid)
+              ->condition('f.uid', 0)
+            )
+            ->condition('f.sid', $sid)
+          )
+        );
+
+      $result = $query->execute()->fetchAllAssoc('cid');
+
+      $flag_names = _flag_get_flag_names();
+      foreach ($result as $cid => $flagging_data) {
+        // At the very least, we need an empty array for the entity ID key in
+        // the cache array, so it counts as present.
+        if (!isset($flag_get_user_flags_cache[$uid][$sid]['comment'][$cid])) {
+          $flag_get_user_flags_cache[$uid][$sid]['comment'][$cid] = array();
+        }
+
+        // If the flagging table gave us no data, we're done with this row.
+        if (is_null($flagging_data->flagging_id)) {
+          continue;
+        }
+
+        // Remove the comment ID field from the row, so it's just the flagging
+        // table row.
+        unset($flagging_data->cid);
+
+        $flag_get_user_flags_cache[$uid][$sid]['comment'][$cid][$flag_names[$flagging_data->fid]] = $flagging_data;
+      }
+
+      // Mark that we've seen this node so we don't process it again.
+      $seen_comment_nids[$comment->nid] = TRUE;
+    }
+
+    // Return data for the comment we were asked about.
+    $user_flags = flag_get_user_flags($this->entity_type, $entity_id, $uid, $sid);
+    return isset($user_flags[$this->name]) ? $user_flags[$this->name] : NULL;
+  }
+
   function get_labels_token_types() {
     return array_merge(array('comment', 'node'), parent::get_labels_token_types());
   }
diff --git a/tests/flag.test b/tests/flag.test
index 27408ee..a9af513 100644
--- a/tests/flag.test
+++ b/tests/flag.test
@@ -1656,3 +1656,129 @@ class FlagHookInvocationsTestCase extends FlagTestCaseBase {
   }
 
 }
+
+/**
+ * Verifies the optimization for comment viewing.
+ */
+class FlagCommentOptimizationTestCase extends FlagTestCaseBase {
+
+  /**
+   * Implements getInfo().
+   */
+  public static function getInfo() {
+    return array(
+      'name' => 'Comment view optimization',
+      'description' => 'Tests that loading of flagging records when viewing all comments on a node works correctly.',
+      'group' => 'Flag',
+    );
+  }
+
+  /**
+   * Implements setUp().
+   */
+  function setUp() {
+    parent::setUp(array(
+      'flag',
+      'comment',
+      'flag_comment_flag_test',
+    ));
+
+    $flag_data = array(
+      'entity_type' => 'comment',
+      'name' => 'test_flag',
+      'title' => 'Test Flag',
+      'global' => 0,
+      'types' => array(),
+      'flag_short' => 'Flag this item',
+      'flag_long' => '',
+      'flag_message' => '',
+      'unflag_short' => 'Unflag this item',
+      'unflag_long' => '',
+      'unflag_message' => '',
+      'unflag_denied_text' => 'You may not unflag this item',
+      'link_type' => 'normal',
+      'weight' => 0,
+      'show_on_form' => 0,
+      'access_author' => '',
+      'show_contextual_link' => 0,
+      'show_in_links' => array(
+        'full' => 1,
+        'teaser' => 1,
+      ),
+      'i18n' => 0,
+      'api_version' => 3,
+    );
+    $this->flag = $this->createFlag($flag_data);
+
+    // Set up comments on article nodes.
+    variable_set('comment_form_location_article', COMMENT_FORM_BELOW);
+
+    // Create test user who can flag and unflag.
+    $this->user = $this->drupalCreateUser(array(
+      'access comments',
+      'post comments',
+      'flag test_flag',
+      'unflag test_flag',
+    ));
+    $this->drupalLogin($this->user);
+
+    // Create an article node.
+    $title = $this->randomName(8);
+    $node = array(
+      'title' => $title,
+      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(32)))),
+      'uid' => $this->user->uid,
+      'type' => 'article',
+      'is_new' => TRUE,
+      'comment' => COMMENT_NODE_OPEN,
+    );
+    $node = node_submit((object) $node);
+    node_save($node);
+
+    $this->nid = $node->nid;
+
+    // Create some comments on the node.
+    $this->cids = array();
+    foreach (range(1, 10) as $i) {
+      $comment = (object) array(
+        'cid' => NULL,
+        'nid' => $node->nid,
+        'pid' => 0,
+        'uid' => $this->user->uid,
+        'status' => COMMENT_PUBLISHED,
+        'subject' => $this->randomName(),
+        'language' => LANGUAGE_NONE,
+        'comment_body' => array(LANGUAGE_NONE => array($this->randomName())),
+      );
+      comment_save($comment);
+
+      $this->cids[$comment->cid] = $comment->cid;
+    }
+
+    // Flag one comment.
+    $this->flag->flag('flag', reset($this->cids));
+  }
+
+  /**
+   * Test viewing multiple comments on a node is optimized.
+   */
+  function testCommentView() {
+    // View the node.
+    $this->drupalGet('node/' . $this->nid);
+
+    // Inspect the tracking variable.
+    // Hooks in the flag_comment_flag_test module will have populated this with
+    // data at various points in the lifecycle of the loaded page.
+    $tracking_variable = variable_get('flag_comment_flag_test_user_flags_cache_tracking', array());
+
+    $this->assertNull($tracking_variable['hook_comment_load'], "The flag_get_user_flags() static cache is empty when the comments are being loaded.");
+
+    // The test module's hook_entity_view() runs after flag's implementation, so
+    // for the first comment view, the cache should be fully populated: all
+    // comments should have an entry.
+    foreach ($this->cids as $cid) {
+      $this->assertNotNull($tracking_variable['hook_entity_view_1'][$this->user->uid][0]['comment'][$cid], "The static cache contained data for comment $cid when comment 1 was being viewed.");
+    }
+  }
+
+}
diff --git a/tests/flag_comment_flag_test/flag_comment_flag_test.info b/tests/flag_comment_flag_test/flag_comment_flag_test.info
new file mode 100644
index 0000000..50fd801
--- /dev/null
+++ b/tests/flag_comment_flag_test/flag_comment_flag_test.info
@@ -0,0 +1,6 @@
+name = Flag Comment Flag Test
+description = Test module for comment flags.
+dependencies[] = flag
+dependencies[] = comment
+core = 7.x
+hidden = TRUE
diff --git a/tests/flag_comment_flag_test/flag_comment_flag_test.module b/tests/flag_comment_flag_test/flag_comment_flag_test.module
new file mode 100644
index 0000000..bf771e1
--- /dev/null
+++ b/tests/flag_comment_flag_test/flag_comment_flag_test.module
@@ -0,0 +1,41 @@
+<?php
+
+/**
+ * @file flag_comment_flag_test.module
+ * Test module for comment flags.
+ */
+
+/**
+ * Implements hook_comment_load().
+ *
+ * This is only called once when viewing a node with comments, and before
+ * hook_entity_view() is invoked. We use this to check the initial state of the
+ * cache.
+ */
+function flag_comment_flag_test_comment_load($comments) {
+  $flag_get_user_flags_cache = drupal_static('flag_get_user_flags');
+
+  // Store the value of the flag_get_user_flags() static cache in the variable,
+  // so the test can retrieve it.
+  $tracking_variable = variable_get('flag_comment_flag_test_user_flags_cache_tracking', array());
+  $tracking_variable['hook_comment_load'] = $flag_get_user_flags_cache;
+  variable_set('flag_comment_flag_test_user_flags_cache_tracking', $tracking_variable);
+}
+
+/**
+ * Implements hook_entity_view().
+ *
+ * Use hook_entity_view() rather than hook_comment_view() so we are in the same
+ * invocation as flag_entity_view().
+ */
+function flag_comment_flag_test_entity_view($entity, $type, $view_mode, $langcode) {
+  if ($type == 'comment') {
+    $flag_get_user_flags_cache = drupal_static('flag_get_user_flags');
+
+    // Store the value of the flag_get_user_flags() static cache in the variable,
+    // so the test can retrieve it.
+    $tracking_variable = variable_get('flag_comment_flag_test_user_flags_cache_tracking', array());
+    $tracking_variable['hook_entity_view_' . $entity->cid] = $flag_get_user_flags_cache;
+    variable_set('flag_comment_flag_test_user_flags_cache_tracking', $tracking_variable);
+  }
+}
