-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Description
In the getSyncedCalendarIdsAsList function located in the folder “helpers”, file “Config.kt”, the current code processes a comma-separated string of calendar IDs inefficiently by using two separate collection operations filter and map.
This code splits the “caldavSyncedCalendarIds” string into a list of substrings, filters out any empty or whitespace-only entries after trimming, and then maps the remaining strings to integers using “Integer.parseInt”. The inefficiency arises from the use of two distinct passes over the data: one for filtering and one for mapping. Each pass creates an intermediate collection (a new List after filter), which increases memory allocations and requires additional iterations. For a large number of calendar IDs, this can lead to unnecessary memory usage and CPU cycles, particularly since both operations could be combined into a single pass.
Proposition:
In this optimized version, “split(",")” produces a list of strings, and “mapNotNull” processes each string in a single pass. For each ID, the string is trimmed, and “takeIf { it.isNotEmpty() }” returns the trimmed string if it’s not empty, or null otherwise. The “toIntOrNull” function then attempts to parse the string to an integer, returning null if parsing fails, “mapNotNull” discards any null results, producing a “List” containing only valid integer IDs. This approach handles both filtering and mapping simultaneously.
The optimization in “getSyncedCalendarIdsAsList” enhances performance by using “mapNotNull” to combine filtering and mapping into a single O(n), reducing memory allocations and CPU usage compared to the original code two step approach (filter then map), which created intermediate lists and doubled iterations. For large inputs, such as hundreds or thousands of calendar IDs, the original code extra list allocations (consuming tens to hundreds of kilobytes) and iterations increased garbage collection pressure, potentially causing UI stuttering or battery drain on Android devices, while the optimized version halves memory usage and saves CPU cycles.

