Skip to content

Commit 0d80c78

Browse files
MustafaKarabulutakondas
authored andcommitted
Micro optimization for matrix multiplication (#255)
* Micro optimization for matrix multiplication * code cs fix * added a comment block for the change
1 parent e156076 commit 0d80c78

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/Math/Matrix.php

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -142,15 +142,24 @@ public function multiply(self $matrix): self
142142
throw new InvalidArgumentException('Inconsistent matrix supplied');
143143
}
144144

145+
$array1 = $this->toArray();
146+
$array2 = $matrix->toArray();
147+
$colCount = $matrix->columns;
148+
149+
/*
150+
- To speed-up multiplication, we need to avoid use of array index operator [ ] as much as possible( See #255 for details)
151+
- A combination of "foreach" and "array_column" works much faster then accessing the array via index operator
152+
*/
145153
$product = [];
146-
$multiplier = $matrix->toArray();
147-
for ($i = 0; $i < $this->rows; ++$i) {
148-
$columns = $matrix->getColumns();
149-
for ($j = 0; $j < $columns; ++$j) {
150-
$product[$i][$j] = 0;
151-
for ($k = 0; $k < $this->columns; ++$k) {
152-
$product[$i][$j] += $this->matrix[$i][$k] * $multiplier[$k][$j];
154+
foreach ($array1 as $row => $rowData) {
155+
for ($col = 0; $col < $colCount; ++$col) {
156+
$columnData = array_column($array2, $col);
157+
$sum = 0;
158+
foreach ($rowData as $key => $valueData) {
159+
$sum += $valueData * $columnData[$key];
153160
}
161+
162+
$product[$row][$col] = $sum;
154163
}
155164
}
156165

0 commit comments

Comments
 (0)