Dart:循环遍历数组并需要索引的传统方法的替代方案

huangapple go评论65阅读模式
英文:

Dart: alternatives for classic way to loop through arrays where index is needed

问题

我需要循环遍历列表项,并需要索引,而不是值。

我知道三种选项:

经典方式:

for (final i = 0; i < list.length; i++) {

使用asMap

for (final i in list.asMap().keys)

使用Iterable

for (final i in Iterable.generate(list.length)) {

非经典选项看起来更容易阅读、编写,且更不容易出错。性能如何?似乎这两种选项都产生可迭代对象,因此它们不应该造成性能开销。这个评估是否正确,或者我漏掉了什么?

英文:

I need to loop through list items and I need index, not value.

I know three options:

Classic:

for (final i = 0; i < list.length; i++) {

With asMap:

for (final i in list.asMap().keys)

With Iterable:

for (final i in Iterable.generate(list.length)) {

Non-classic options look to be easier to read, write and less error prone.
How about performance? It seems both options produce iterable, so they should not create performance overhead. Is it correct assessment or I am missing something?

答案1

得分: 2

以下是翻译好的内容:
Micro benchmark here (usual caveats apply) https://gist.github.com/jakemac53/16c782ed92f6bbceb98ad83cd257c760.

If your code is perf sensitive, use the "classic" for loop.

英文:

Micro benchmark here (usual caveats apply) https://gist.github.com/jakemac53/16c782ed92f6bbceb98ad83cd257c760.

If your code is perf sensitive, use the "classic" for loop.

答案2

得分: 1

不错的选择,目前对于传统方式的现有替代方案在性能方面并不太理想,但正在进行改进,以引入更好的循环列表方式:https://github.com/dart-lang/collection/pull/259#discussion_r1090563595

目前,这个扩展将使循环更加方便:

extension Indexes<T> on List<T> {
  Iterable<int> get indexes sync* {
    for (var i = 0; i < length; i++) yield i;
  }
}

然后我们可以这样写:

for (final i in list.indexes)
英文:

While existing alternatives for the classic way are not great from performance perspective, there is work in progress to introduce a better way to loop lists: https://github.com/dart-lang/collection/pull/259#discussion_r1090563595

For now you the extension will enable nice looping:

extension Indexes&lt;T&gt; on List&lt;T&gt; {
  Iterable&lt;int&gt; get indexes sync* {
    for (var i = 0; i &lt; length; i++) yield i;
  }
}

Then we can write:

for (final i in list.indexes)

答案3

得分: 0

使用package:collection,您可以在可迭代对象上使用.mapIndexed,以同时获得元素和元素的索引。

final result = someList.mapIndexed((n, e) => "item $n is $e");
英文:

Using package:collection, you can get a .mapIndexed on an Iterable to give you both the item and the index of the item.

final result = someList.mapIndexed((n, e) =&gt; &quot;item $n is $e&quot;);

huangapple
  • 本文由 发表于 2023年2月7日 03:47:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定