dart-lang / dart-lang/language

A fast and safe List.cast

Open
#1,189 30 comments 1 reaction 0 assignees View on GitHub
nnbd
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

A pattern we see in some of Flutter's hottest code paths is:

```dart
List algorithm(List oldList) {
List newList = List.generate(oldList.length, null, growable: false);
// fill in newList using oldList
...
// the algorithm guarantees that newList has no nulls in it
return newList.cast();
}
```

The cast introduces a hidden expense: every access to the new list in the future checks for nulls.

Right now we're planning on working around it like this:

```dart
class _NullFoo extends Foo {
static Foo instance = _NullFoo();
}

List algorithm(List oldList) {
List newList = List.generate(oldList.length, _NullFoo.instance, growable: false);
// fill in newList using oldList
...
// the algorithm guarantees that newList has no instances of _NullFoo in it
return newList;
}
```

...but it's awkward to do this and doesn't really reflect the desire, which is for an equivalent of "late".

Proposal: List could have a new method, "castAndClear" or "destructiveCast" or some such, which returns a new List cast as specified, but using the backing store of the old list, and neutering the old list (so it doesn't provide a back door to breaking the type system).

Contributor guide

Open the contributing guide

Research direction

Start with the issue's List.cast examples and the proposed castAndClear or destructiveCast behavior. Determine the API and semantics for reusing the backing store while neutering the original list; done means the language-design proposal has a decided specification and implementation direction.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.