Skip to content

LastWhereOrNull is Inefficient on Large Lists #950

@PvtPuddles

Description

@PvtPuddles

Hello,

List.lastWhereOrNull(...) (from IterableExtensions) is inefficient for lists compared to calling List.reversed.firstWhereOrNull(...).

Consider this example:

final myList = List.generate(1_000_000, (i) => i);
final slowImpl = myList.lastWhereOrNull((i) => i >= 900_000);
final fastImpl = myList.reversed.firstWhereOrNull((i) => i >= 900_000);

In this case, slowImpl is computed by iterating through 1,000,000 elements. On the other hand, fastImpl completes after iterating through only 1,000 elements.

Since iterable does not have a reversed property (and since we would not know if it is efficient if there was one), I propose creating a ListExtensions extension (an idea also floated here) that can take advantage of List.reversed being an O(1) operation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions