コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】複数の小さなテキストファイルの書き込みを foreach と Parallel.ForEach で実行した場合の速度検証

検証内容

  • 10,000 回 File.WriteAllText を実行する処理を foreach で書いた場合と
    Parallel.ForEach で書いた場合の速度を検証

検証環境

  • Unity 2021.2.7f1
  • Windows IL2CPP ビルド
  • Android IL2CPP ビルド

検証結果(Unity エディタ)

項目 かかった時間
foreach 2.76 秒
Parallel.ForEach 1.90 秒

検証結果(Windows IL2CPP ビルド)

項目 かかった時間
foreach 2.41 秒
Parallel.ForEach 1.67 秒

検証結果(Android IL2CPP ビルド)

項目 かかった時間
foreach 158.9 秒
Parallel.ForEach 200.3 秒

検証用スクリプト

using System.Diagnostics;
using System.IO;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;

public sealed class Example : MonoBehaviour
{
    private void Awake()
    {
        const int count = 10_000;

        var array = Enumerable.Range( 0, count ).ToArray();

        var temporaryPath = $"{Application.persistentDataPath}/Temp";

        if ( Directory.Exists( temporaryPath ) )
        {
            Directory.Delete( temporaryPath, true );
        }

        Directory.CreateDirectory( temporaryPath );

        var sw = Stopwatch.StartNew();

        foreach ( var i in array )
        {
            var path = $"{temporaryPath}/{i.ToString()}.txt";

            File.WriteAllText( path, "" );
        }

        Debug.LogWarning( "#### foreach: " + sw.Elapsed.TotalSeconds );

        Directory.Delete( temporaryPath, true );

        Directory.CreateDirectory( temporaryPath );

        sw = Stopwatch.StartNew();

        System.Threading.Tasks.Parallel.ForEach
        (
            array, i =>
            {
                var path = $"{temporaryPath}/{i.ToString()}.txt";

                File.WriteAllText( path, "" );
            }
        );

        Debug.LogWarning( "#### Parallel.ForEach: " + sw.Elapsed.TotalSeconds );
    }
}