r/FlutterDev • • Oct 02 '26

Discussion That innocent-looking compareTo callback might be freezing your 60 FPS timeline

A few days ago, a Flutter developer wrote a profiling post about sorting 10,000 timeline events. Under a section they called "The Original Sin", they pointed out the culprit:

items.sort((a, b) => DateTime.parse(a.start).compareTo(DateTime.parse(b.start)));

In an O(N log N) sort, that callback runs over 215,000 times for 10,000 items. On a mobile isolate, parsing 215,000 ISO strings takes 180ms+ and drops a dozen frames.

To fix it, they mapped the list to a temporary helper object with pre-parsed dates, sorted by the cached key, and unwrapped it.

That Map -> Sort -> Map pattern was actually what I posted to Usenet back in 1994 (what became known as the Schwartzian Transform). But what surprised me running benchmarks in modern Dart: package:collection's sortedBy does not cache keys either—it still ran 127,000 redundant key evaluations because mergeSortBy re-evaluates keys during merges.

With Dart 3 records, you don't even need throwaway helper classes anymore—a boxed record one-liner or simple extension method runs in 14ms (13x faster).

Have you ever caught a subtle frame stutter hiding inside a sort or compare callback?

28 Upvotes

19 comments sorted by

11

u/driftwood_studio Oct 02 '26

I get the point, and don't disagree... but... I mean anyone who's dealing with an application that's sorting 10,000 of something who hasn't bothered to do a little extremely basic profiling and educate themselves even minimally about the very well documented principles of sorting algorithms... and who is writing code that's doing that sorting in a way that blocks the main rendering thread...

I'm not sure this kind of information is going to help them. They're not the programmers who even really understand there's something they don't know here.

You have to not really know what you're doing to some degree to even get into this kind of situation.

Which... welcome to the imminent future of vibe coded software by non-developers.

7

u/RandalSchwartz Oct 02 '26

10,000 items was chosen for the benchmark to show the mathematical divergence clearly, but remember: on a 120Hz mobile display, your entire frame budget is just 8.3 milliseconds. You don't need 10,000 items to drop frames—a list of 300 activities with string parsing or JSON traversal in compareTo will easily blow through 8ms on a mid-range phone.

Furthermore, in languages like Python, list.sort(key=...) does extract keys once. A developer coming to Dart who reaches for package:collection's iterable.sortedBy(keyOf) might reasonably assume it caches keys too, without realizing mergeSortBy re-evaluates keyOf on every comparison (O(N log N) calls).

And to Hammad's credit: he did profile his app, found the bottleneck in DevTools, and fixed it. Articles like this just help explain the underlying computer science so the next dev doesn't have to spend an afternoon in the timeline profiler to understand why.

7

u/samrawlins Oct 02 '26

Love the post, but the title is misleading.

That innocent-looking DateTime.parse call which is repeatedly called thousands of times on each value, might be freezing your 60 FPS timeline.

The compareTo calls are not reduced and are not the problem.

This reminds me of another foot gun: iterating over a lazy Iterable repeatedly:

var i = manyObjects.map((e) => e.expensiveCalculation());

var x = i.where((e) => e.isFoo);
var y = i.any((e) => e.isBar);

i is an Iterable, not a List. Each time you iterate over it, you repeat those expensive calls. I've considered a lint rule for this but never been able to design one that doesn't report a lot of false positives.

Similarly, doing expensive calculations in a for-loop that don't depend on the loop variable:

for (var e in items) {
  var x = expensiveCalculation();
  print(e.foo(x));
}

It would be easier to write this lint rule, but maybe just not very high value.

-14

u/RandalSchwartz Oct 02 '26

Fair point, Sam! You're completely right—DateTime.compareTo itself is just a fast integer comparison on microseconds; the "crime" was burying two calls to DateTime.parse() inside the sort comparison callback so that an O(N log N) sort executed it 200,000+ times. "Innocent-looking sort callback" was the intended thought, but the title condensed it a bit too far!

And that lazy Iterable trap you mentioned is huge. Because Iterable.map() returns a lazy MappedIterable rather than snapshotting a list, people don't realize every terminal consumer (.any(), .where(), .length) re-runs that mapping function from scratch across the entire sequence.

I see developers get bitten by that all the time when chaining queries or passing iterables across layers. Designing a lint for that without false positives on cheap pure getters must be a nightmare, but it really is one of the classic Dart performance traps.

Thanks for reading and chiming in!

6

u/Wi42 Oct 02 '26 edited Oct 02 '26

I would almost bet money that that answer was completely AI generated.

-11

u/RandalSchwartz Oct 02 '26

And yet, that doesn't change the accuracy. I vet everything I post, and stand by the words that have my name on it. Stop being a modern luddite, please.

1

u/official_marcoms Oct 08 '26

Most of your comments seem to be AI generated. I’m curious if you don’t find anything dystopian about a future where all online conversations are delegated to LLMs and nobody is actually talking to each other?

20

u/eibaan Oct 02 '26

Oh, Randal-bot is back.

14

u/Honey-Entire Oct 03 '26

Thanks for all those words, Claude. I’m impressed you’ve discovered the novel idea of avoiding iterating over lists multiple times.

3

u/kastanCZ Oct 05 '26

internet is dead fr

4

u/virtualmnemonic Oct 03 '26

You shouldn't need to parse it to sort properly to begin with.

4

u/stumblinbear Oct 03 '26

Yeah, this is just a blatant violation of parse don't validate. I really had to beat it into my team to type things as early as possible, especially identifiers. It was surprisingly difficult to get them to learn to make extension types for user IDs or other things.

Ain't no way am I working in a codebase where the convention for knowing that a string is a user ID is built into the variable name

1

u/Lanky-Foundation8727 Oct 03 '26

I don't think caching keys is the better choice universally. Maybe if calculating the key is slow, like in this case

but also it might be it's just a field getter

in that case, allocating a new list, allocating a tuple for every single element, sorting, then mapping that back or alternatively, allocating a hashmap as a cache for the keys might be slower. not sure how well dart optimizes this but in theory it can be zero-cost that way.

1

u/RandalSchwartz Oct 03 '26

Yeah, read the linked article... I say this exactly. Having nearly 3 decades of experience with map-sort-map, I've seen it all. :)