0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityC#のListのforeach GCゴミ

Last updated at Posted at 2020-04-24

はじめに

河合さんの記事, 今はどうなっているのかな?という調査です.
neue cc - C#のGCゴミとUnity(5.5)のコンパイラアップデートによるListのforeach問題解決について
有名なforeachのGCゴミについてです.

テストコード

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.UI;

public class ForEach : MonoBehaviour
{
    [SerializeField]
    private Button button_ = null;

    private int[] array_ = new int[] { 1, 2, 3, 4, 5 };
    private List<int> list_ = new List<int> { 1, 2, 3, 4, 5 };

    private void Start()
    {
        button_.onClick.AddListener(onClick);
    }

    private void onClick()
    {
        Profiler.BeginSample("GCAllocCheck:Array");
        foreach(var item in array_) { }
        Profiler.EndSample();

        Profiler.BeginSample("GCAllocCheck:List");
        foreach(var item in list_) { }
        Profiler.EndSample();
    }
}

結果

バージョンごとに調査(したい).

5.6.4f1

起動後初めてボタンを押下した場合だけ, ゴミが出る. 原因は未調査.

  • 1回目
    GCAlloc5.6.4f1_00.png

  • 2回目
    GCAlloc5.6.4f1_01.png

2019.2.9f1

起動後初めてボタンを押下した場合だけ, ゴミが出る. 原因は未調査.

  • 1回目
    GCAlloc2019.2.9f1_00.png

  • 2回目
    GCAlloc2019.2.9f1_01.png

まとめ

エディタ上で調査しているため, ビルドすると異なる可能性がある. もちろんターゲットにより異なる可能性がある.
原因はGetEnumeratorに関連しているため, ゴミが出る場合は, LINQを使うと目も当てられない結果になるだろう(調査していないため推測).

1回目のゴミ推測

これ, boxingのための領域か何かかな. 詳しく調査していないため, 2回目以降必ずゴミが出ないかは不明.
推測が正解なら気にしなくてもよさそう.
コードの読みやすさ次第で使用できそうだが, クリティカルな箇所では for にしておく方がよさそう.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?