google / google/built_value.dart

request to support automatic interning of `Built` objects

Open
#750 6 comments 0 reactions 1 assignee Claimed by @davidmorgan View on GitHub
p2 / feature request
Dominant language
Dart
Stars
886
Forks
195
Avg merge
1d 11h
Merged PRs (30d)
4

Description

It would be great to have an option to support automatic interning of `Built` objects. (caching them so that objects that are equal according to `==` are not duplicated, speeding up equality comparisons)

In Dart 2.6, it is possible to use [extension methods](https://medium.com/dartlang/extension-methods-2d466cd8b308) to add a `intern()` method to `Built` types:

```dart
Set _cache_built_value = {};

extension BuiltExtensionIntern, B extends Builder> on Built {
V intern() {
Set cache = _cache_built_value;
Built cached_value = cache.lookup(this);
if (cached_value == null) {
cache.add(this);
return this;
} else {
return cached_value;
}
}
}
```

Now, I can call `intern()` on instances of `Built`, e.g.,

```dart
var myValue = (MyValueBuilder()..field1="abc").build().intern();
```

However, it would be great if this could be automated to happen on every call to `build()`. For example, if I have a nested builder, then I have to assign a `Builder` object to it, not a `Built`, so it's not an option for my code to call `intern()` immediately after. The call to `build()` happens in the library code where I cannot control it.

One option is a special subclass of `Built` that could be implemented instead of `Built`?

Of course the same thing would be useful for `BuiltList`, `BuiltMap`, etc.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.