検証内容
- 約 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 ); } }