Reputation: 3282
In Dart, is there any difference between accessing list elements using elementAt
and the []
operator?
var sensors = ["ir", "ultrasound", "laser"];
void main() {
print(sensors.elementAt(1));
print(sensors[1]);
}
Upvotes: 7
Views: 1960
Reputation: 1663
There is a difference, try to run this with and without dart2native
compilation
for my MacBook it will be:
mb:mobile ivan$ dart test.dart
iterable 448
list 19
list bracket 36
mb:mobile ivan$ dart2native test.dart -o zzz
mb:mobile ivan$ ./zzz
iterable 2
list 1
list bracket 0
If i decrease elementsCount
to 10000000
:
mb:mobile ivan$ dart test.dart
iterable 484
list 19
list bracket 9
mb:mobile ivan$ dart2native test.dart -o zzz
mb:mobile ivan$ ./zzz
iterable 2
list 1
list bracket 0
and for elementsCount = 100000000
:
mb:mobile ivan$ dart2native test.dart -o zzz
mb:mobile ivan$ ./zzz
iterable 13
list 32
list bracket 1
Upvotes: -1
Reputation: 1099
The .elementAt()
method is coming with the Iterable
class. It works with all iterables, not only Lists
.
Some iterables may have more efficient ways to find the element, so do Lists, using the bracket notation.
The bracket notation will call .elementAt() implicity. The bracket notation does not serve any additional meaning, only ease of use - as many would say, it's a "syntactical sugar". This is what I mean by efficiency. You can use it with less typing. I did not mean algorithmic efficiency, like finding the element faster in a large List
or anything like that.
Also, Lists in Dart are similar to the so called "arrays" in many languages. These old-school languages use bracket notation to identify array elements. So the bracket notation is also a tradition and serves the purpose of getting started easily with Dart, when you come from a background of Java or C# ... etc.
Upvotes: 4