Wednesday, September 17, 2025
From Timestamp Manipulation to Custom Comparators: A Performance Story

When developing in the WhatsApp environment that requires custom chat ordering, developers face a choice: manipulate chat data to fit the existing sorting logic, or implement custom sorting behavior. This post explores how we migrated from an expensive timestamp manipulation approach to an efficient custom comparator solution.
The Problem
Our chat management system required custom sorting logic based on different priority states with specific ordering requirements that could not be achieved through standard timestamp-based sorting alone.

Original order is chronological (still used in 'All' view)
Initial Approach: Timestamp Manipulation
We initially modified chat timestamps to leverage existing sorting:
Problems
The main problems with this approach were tied to performance, data integrity, memory usage, and restoration complexity. Each sort required O(n) timestamp generation, which slowed down the process significantly. At the same time, original timestamps were overwritten, compromising data integrity. To mitigate this, caching of the original values became necessary, introducing additional memory overhead. Finally, restoring the original order proved to be costly and complex, adding unnecessary friction to the workflow.
The Solution: Custom Comparator
Instead of mutating chat data, we used the collection’s _comparator
property:
Restoration is instant:

Pending view implemented, using custom chat ordering (instead of chronological)
Performance Benefits
The new approach delivered clear performance benefits without compromising maintainability. Since chat objects remain unchanged, there is zero data mutation, ensuring integrity and reliability. Restoration became about 50 times faster by relying on an O(1) comparator swap instead of O(n) timestamp restoration. It is also memory efficient, as no duplication or caching is required. Finally, by keeping a clean separation between the data and the sorting logic, the solution is far more maintainable and easier to extend.
Key Takeaway
When your custom requirements don’t fit the existing data model, resist the urge to manipulate the data. Instead, look for framework extension points that allow you to implement custom behavior while preserving data integrity. The most elegant solutions often work with the framework rather than around it.
Sometimes the best optimization is not doing the work at all – in this case, not manipulating data when you can manipulate behavior instead.