Skip to content

Commit be70d8c

Browse files
committed
Improve performance by sorting timers only on demand
1 parent efd037c commit be70d8c

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/Timer/Timers.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ final class Timers
1717
private $time;
1818
private $timers = array();
1919
private $schedule = array();
20+
private $sorted = true;
2021

2122
public function updateTime()
2223
{
@@ -33,7 +34,7 @@ public function add(TimerInterface $timer)
3334
$id = spl_object_hash($timer);
3435
$this->timers[$id] = $timer;
3536
$this->schedule[$id] = $timer->getInterval() + microtime(true);
36-
asort($this->schedule);
37+
$this->sorted = false;
3738
}
3839

3940
public function contains(TimerInterface $timer)
@@ -49,6 +50,12 @@ public function cancel(TimerInterface $timer)
4950

5051
public function getFirst()
5152
{
53+
// ensure timers are sorted to simply accessing next (first) one
54+
if (!$this->sorted) {
55+
$this->sorted = true;
56+
asort($this->schedule);
57+
}
58+
5259
return reset($this->schedule);
5360
}
5461

@@ -59,6 +66,12 @@ public function isEmpty()
5966

6067
public function tick()
6168
{
69+
// ensure timers are sorted so we can execute in order
70+
if (!$this->sorted) {
71+
$this->sorted = true;
72+
asort($this->schedule);
73+
}
74+
6275
$time = $this->updateTime();
6376

6477
foreach ($this->schedule as $id => $scheduled) {
@@ -78,7 +91,7 @@ public function tick()
7891
// re-schedule if this is a periodic timer and it has not been cancelled explicitly already
7992
if ($timer->isPeriodic() && isset($this->timers[$id])) {
8093
$this->schedule[$id] = $timer->getInterval() + $time;
81-
asort($this->schedule);
94+
$this->sorted = false;
8295
} else {
8396
unset($this->timers[$id], $this->schedule[$id]);
8497
}

0 commit comments

Comments
 (0)