検証内容
- 約 100 MB の文字列を 100 回 File.WriteAllText する処理を
foreach で書いた場合と Parallel.ForEach で書いた場合の速度を検証
検証環境
- Unity 2021.2.7f1
- Windows IL2CPP ビルド
- Android IL2CPP ビルド
検証結果(Unity エディタ)
項目 |
かかった時間 |
foreach |
40.5 秒 |
Parallel.ForEach |
12.8 秒 |
検証結果(Windows IL2CPP ビルド)
項目 |
かかった時間 |
foreach |
40.3 秒 |
Parallel.ForEach |
12.0 秒 |
検証結果(Android IL2CPP ビルド)
項目 |
かかった時間 |
foreach |
228.2 秒 |
Parallel.ForEach |
215.9 秒 |
検証用スクリプト
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using Debug = UnityEngine.Debug;
public sealed class Example : MonoBehaviour
{
private void Awake()
{
const int count = 100;
var array = Enumerable.Range( 0, count ).ToArray();
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();
foreach ( var i in array )
{
var path = $"{temporaryPath}/{i.ToString()}.txt";
File.WriteAllText( path, content );
}
Debug.Log( "#### 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, content );
}
);
Debug.Log( "#### Parallel.ForEach: " + sw.Elapsed.TotalSeconds );
}
}