Improve performance of `Event.__lt__` by avoiding temporary tuple allocation
Summary
While benchmarking heavy event scheduling workloads, I noticed that Event.__lt__ currently performs tuple-based comparison:
return (self.time, self.priority, self.unique_id) < (
other.time,
other.priority,
other.unique_id,
)
Since heap operations can trigger a very large number of comparisons, this results in repeated temporary tuple allocations during scheduling. I experimented with replacing the tuple comparison with an explicit field-by-field comparison:
if self.time != other.time:
return self.time < other.time
if self.priority != other.priority:
return self.priority < other.priority
return self.unique_id < other.unique_id
This avoids tuple creation while preserving identical ordering semantics
Benchmark Results Using a recurring-event benchmark with increasing load:
Tuple-based comparison
- 5k events: ~8–9s
- 20k events: ~90–130s
- 50k events: ~210–330s
Manual comparison
- 5k events: ~6–8s
- 20k events: ~69–75s
- 50k events: ~178–190s
The performance difference becomes more noticeable as the number of scheduled events increases. All existing mesa.time tests pass with the manual comparison implementation.