GarbageCollector.GCMode を使用して、ランタイムにガベージコレクションを無効にすることができます。これにより、CPU の急上昇を防ぐことができますが、ガベージコレクターは参照を持たなくなったオブジェクトを収集しないため、アプリケーションのメモリ使用量は減少しません。
注意: ガベージコレクターを無効にするには、慎重なメモリ管理が必要です。慎重にメモリを管理しないと、アプリケーションがメモリ不足になるまでマネージヒープが継続的に拡張され、OS がアプリケーションをシャットダウンしてしまいます。
以下の API を使用して、自動ガベージコレクターの制御を微調整することができます。
System.GC.Collect
: フルブロッキングガベージコレクションを実行します。System.Gc.Collect
を使用しても効果はありません。System.GC.Collect
を使ってフルコレクションを実行することができます。GarbageCollection.CollectIncremental
: インクリメンタル ガベージコレクションを実行します。ガベージコレクションを無効にするのはアプリケーションの中でも短い時間、パフォーマンスが重要な部分だけで、必要なメモリの割り当て量を計算して制御することができる場合にすべきです。その後、すぐにガベージコレクションを有効にし、プロジェクトを頻繁にプロファイルして、マネージヒープが大きくなりすぎる原因となる追加のマネージアロケーション (割り当て) が発生しないようにする必要があります。
ガベージコレクターを無効にする場合、アプリケーションがガベージコレクションを行うのを止めるわけではありません。System.GC.Collect
の呼び出しの効果が無効にされ、コレクションを開始しなくなります。時間の経過とともにメモリ使用量が増加するのを防ぐために、メモリ管理には注意が必要です。理想的には、ガベージコレクターを無効にする前にすべてのメモリを割り当て、無効になっている間は追加の割り当てを避けるべきです。
ガベージコレクターを無効にするのは、長期間存続する割り当ての場合だけにするのが良い実践方法です。例えば、ゲームのレベルがロードされる前にそのレベルに必要なすべてのメモリを割り当ててから、ガベージコレクターを無効にしてレベル中のパフォーマンスのオーバーヘッドを避けます。レベルが完了しすべてのメモリが解放された後にガベージコレクターを再び有効にし、System.GC.Collect
を使用して次のレベルをロードする前にメモリを再利用できます。
ランタイムにガベージコレクションを有効/無効にする方法の詳細は、GarbageCollector のページを参照してください。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.