Browse Source

A couple micro-optimizations related to counting results from ResultSet

Jose Lorenzo Rodriguez 11 years ago
parent
commit
cefcfcf7b3
3 changed files with 13 additions and 3 deletions
  1. 4 0
      src/Datasource/ResultSetDecorator.php
  2. 5 3
      src/ORM/ResultSet.php
  3. 4 0
      tests/TestCase/ORM/QueryTest.php

+ 4 - 0
src/Datasource/ResultSetDecorator.php

@@ -37,6 +37,10 @@ class ResultSetDecorator extends Collection implements Countable, Serializable,
  * @return int
  */
 	public function count() {
+		if ($this->getInnerIterator() instanceof Countable) {
+			return $this->getInnerIterator()->count();
+		}
+
 		return count($this->toArray());
 	}
 

+ 5 - 3
src/ORM/ResultSet.php

@@ -21,6 +21,7 @@ use Countable;
 use Iterator;
 use JsonSerializable;
 use Serializable;
+use SplFixedArray;
 
 /**
  * Represents the results obtained after executing a query for a specific table
@@ -133,9 +134,10 @@ class ResultSet implements Countable, Iterator, Serializable, JsonSerializable {
 		$this->_hydrate = $this->_query->hydrate();
 		$this->_entityClass = $repository->entityClass();
 		$this->_useBuffering = $query->bufferResults();
+		$this->count();
 
-		if ($statement) {
-			$this->count();
+		if ($this->_useBuffering) {
+			$this->_results = new SplFixedArray($this->_count);
 		}
 	}
 
@@ -475,7 +477,7 @@ class ResultSet implements Countable, Iterator, Serializable, JsonSerializable {
  */
 	protected function _bufferResult($result) {
 		if ($this->_useBuffering) {
-			$this->_results[] = $result;
+			$this->_results[$this->_index] = $result;
 		}
 	}
 

+ 4 - 0
tests/TestCase/ORM/QueryTest.php

@@ -966,6 +966,10 @@ class QueryTest extends TestCase {
 			->method('fetch')
 			->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
 
+		$statement->expects($this->once())
+			->method('rowCount')
+			->will($this->returnValue(2));
+
 		$query->expects($this->once())
 			->method('execute')
 			->will($this->returnValue($statement));