-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Description
In the implementation of the reminder handling logic in “TaskActivity.kt” (and similarly in different activity.kt files), the code filters and sorts a list of reminders inefficiently by creating multiple intermediate collections.
This code performs three operations in sequence: filter removes reminders where minutes equals “REMINDER_OFF”, sortedBy sorts the filtered list by minutes, and “toMutableList() as ArrayList” converts the result to an ArrayList. Each operation creates a new collection, filter produces an intermediate List, sortedBy creates another, and toMutableList creates a third. For a list of n reminders, this results in O(n) time for filtering, O(n log n) for sorting, and O(n) for the final conversion, with three list allocations. These allocations increase memory usage and garbage collection pressure, which can cause UI stuttering or battery drain on Android devices.
Proposition:
The “let { ArrayList(it) }” block converts the result directly to an ArrayList, avoiding the “toMutableList().as ArrayList” cast. While the optimized code still uses filter and sortedBy separately, it reduces unnecessary conversions and clarifies the intent by using let to create the final ArrayList in one step. Compared to the original, it avoids the redundant toMutableList() allocation and the risky cast.
Additionally, the optimized code is more expressive and maintainable, as “let { ArrayList(it) }” clearly indicates the intent to produce an ArrayList, reducing the likelihood of future errors during code modifications. While a single step approach using TreeSet or fold could further reduce allocations by filtering and sorting simultaneously, the provided change is a practical improvement that balances simplicity and performance.

