dart-lang / dart-lang/language
Allow objects to be eliminated
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
[Edit: Adjusted `DateTime` examples to create a situation which is directly relevant for a 'static class'.]
There are some situations where an object is created in order to hold some data, and some instance methods are invoked on that object in order to compute results or perform actions based on that data. But the object itself is not needed for any other purpose than holding the given data during those method invocations. For instance:
```dart
main() {
var currentMonth = DateTime.now().month;
var moonLandingDay = DateTime.parse("1969-07-20 20:18:04Z").weekday;
print("Current month: $currentMonth, Moon landing day: $moonLandingDay");
var fullString = (StringBuffer()
..write("Use a StringBuffer")
..writeAll(["for ", "efficient ", "string ", "creation "])
..write("if you are ")
..write("building lots of strings"))
.toString();
}
```
(Examples derived from the [DateTime DartDoc](https://api.dartlang.org/stable/2.2.0/dart-core/DateTime-class.html) and an example in [Seth's blog entry on strings in Dart](http://blog.sethladd.com/2012/01/strings-in-dart.html)).
If such objects are indeed never needed at all (except as storage locations for the data included in the construction) then we could allow an optimization whereby the allocation of a new object is eliminated, the data is stored in the run-time stack, and the computations are performed in a top-level function.
Contributor guide
Assessment
This issue has not been assessed yet.