Array/List iteration without extra object allocations

Matthias :

I'm working on a game written in Kotlin and was looking into improving GC churn. One of the major sources of churn are for-loops called in the main game/rendering loops that result in the allocation of iterators.

Turning to the documentation, I found this paragraph:

A for loop over an array is compiled to an index-based loop that does not create an iterator object.

If you want to iterate through an array or a list with an index, you can do it this way:

for (i in array.indices)
  print(array[i])

Note that this “iteration through a range” is compiled down to optimal implementation with no extra objects created.

https://kotlinlang.org/docs/reference/control-flow.html#for-loops

Is this really true? To verify, I took this simple Kotlin program and inspected the generated byte code:

fun main(args: Array<String>) {
    val arr = arrayOf(1, 2, 3)
    for (i in arr.indices) {
        println(arr[i])
    }
}

According to the quote above, this should not result in any objects allocated, but get compiled down to a good old pre-Java-5 style for-loop. However, what I got was this:

      41: aload_1
      42: checkcast     #23                 // class "[Ljava/lang/Object;"
      45: invokestatic  #31                 // Method kotlin/collections/ArraysKt.getIndices:([Ljava/lang/Object;)Lkotlin/ranges/IntRange;
      48: dup
      49: invokevirtual #37                 // Method kotlin/ranges/IntRange.getFirst:()I
      52: istore_2
      53: invokevirtual #40                 // Method kotlin/ranges/IntRange.getLast:()I
      56: istore_3
      57: iload_2
      58: iload_3
      59: if_icmpgt     93

This looks to me as if a method called getIndices is called that allocates a temporary IntRange object to back up bounds checking in this loop. How is this an "optimal implementation" with "no extra objects created", or am I missing something?

UPDATE: So, after toying around a bit more and looking at the answers, the following appears to be true for Kotlin 1.0.2:

Arrays:

  • for (i in array.indices): range allocation
  • for (i in 0..array.size): no allocation
  • for (el in array): no allocation
  • array.forEach: no allocation

Collections:

  • for (i in coll.indices) range allocation
  • for (i in 0..coll.size): no allocation
  • for (el in coll): iterator allocation
  • coll.forEach: iterator allocation
Michael :

As far as I know the only allocation-less way to define a for loop is

for (i in 0..count - 1)

All other forms lead to either a Range allocation or an Iterator allocation. Unfortunately, you cannot even define an effective reverse for loop.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Iteration over multidimesionn ArrayList

ArrayList to Object[][]

Better iteration pattern without enumerating

get one object in queryset iteration

Typescript / Angular 5 - iteration on a object

eval() not working while object iteration

How can I return a struct's mutable member from and iterator's next method without allocations?

Duplicate strings in ArrayList of object

Object iteration in react component render is not working

linear graphView without sorting arraylist

Jackson: Convert JSON to object: ArrayList of objects with arraylist of objects with arraylist of objects

how to remove association in sequelize without extra query?

Java , Removing object from ArrayList

JAVA writing and loading an Object ArrayList

Get Object type of class for ArrayList

Object Oriented adding items to an a arrayList

Send SimpleAdapter or ArrayList<Object> with Intent

C# Form is displaying an extra object

How do you stop a loop from adding an extra iteration of a character in C++?

Unique values from 1D-array, without iteration

How to select result from dataframe according to specific pairs without iteration?

How to create arraylist without one element from another arraylist

ArrayList <ArrayList <Integer >>をArrayList <ArrayList <Object >>に変換できません

ByteBuffer memory allocations

Thymeleaf Without Object Classes?

How to combine sync object iteration and async code in python?

Reference is able to refer to a different object (not in the iteration/loop body)

XPath iteration Exception: "An attempt was made to use an object that is not, or is no longer, usable"

iterate through JSON object with pause before next iteration

TOP 一覧

  1. 1

    Unity:未知のスクリプトをGameObject(カスタムエディター)に動的にアタッチする方法

  2. 2

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  3. 3

    Ansibleで複数行のシェルスクリプトを実行する方法

  4. 4

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  5. 5

    Crashlytics:コンパイラー生成とはどういう意味ですか?

  6. 6

    GoDaddyでのCKEditorとKCfinderの画像プレビュー

  7. 7

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  8. 8

    Chromeウェブアプリのウェブビューの高さの問題

  9. 9

    モーダルダイアログを自動的に閉じる-サーバーコードが完了したら、Googleスプレッドシートのダイアログを閉じます

  10. 10

    Windows 10の起動時間:以前は20秒でしたが、現在は6〜8倍になっています

  11. 11

    Reactでclsxを使用する方法

  12. 12

    ファイル内の2つのマーカー間のテキストを、別のファイルのテキストのセクションに置き換えるにはどうすればよいですか?

  13. 13

    MLでのデータ前処理の背後にある直感

  14. 14

    グラフからテーブルに条件付き書式を適用するにはどうすればよいですか?

  15. 15

    Pythonを使用して同じ列の同じ値の間の時差を取得する方法

  16. 16

    mutate_allとifelseを組み合わせるにはどうすればよいですか

  17. 17

    ネットワークグラフで、ネットワークコンポーネントにカーソルを合わせたときに、それらを強調表示するにはどうすればよいですか?

  18. 18

    テキストフィールドの値に基づいて UIslider を移動します

  19. 19

    BLOBストレージからデータを読み取り、Azure関数アプリを使用してデータにアクセスする方法

  20. 20

    PowerShellの分割ファイルへのヘッダーの追加

  21. 21

    ソートされた検索、ターゲット値未満の数をカウント

ホットタグ

アーカイブ