コガネブログ

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

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

検証内容

  • 約 100 MB の文字列を 100 回 File.WriteAllText する処理を
    for で書いた場合と Parallel.For で書いた場合の速度を検証

検証環境

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

検証結果(Unity エディタ)

項目 かかった時間
for 40.6 秒
Parallel.For 14.8 秒

検証結果(Windows IL2CPP ビルド)

項目 かかった時間
for 24.9 秒
Parallel.For 12.0 秒

検証結果(Android IL2CPP ビルド)

項目 かかった時間
for 235 秒
Parallel.For 236 秒

検証用スクリプト

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

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

        var stringBuilder = new StringBuilder();

        for ( var i = 0; i < 100_000_000; i++ )
        {
            stringBuilder.Append( "a" );
        }

        var content = stringBuilder.ToString();

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

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

        Directory.CreateDirectory( temporaryPath );

        var sw = Stopwatch.StartNew();

        for ( var i = 0; i < count; i++ )
        {
            var path = $"{temporaryPath}/{i.ToString()}.txt";

            File.WriteAllText( path, content );
        }

        Debug.Log( "#### for: " + sw.Elapsed.TotalSeconds );

        Directory.Delete( temporaryPath, true );

        Directory.CreateDirectory( temporaryPath );

        sw = Stopwatch.StartNew();

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

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

        Debug.Log( "#### Parallel.For: " + sw.Elapsed.TotalSeconds );
    }
}