配列のメモリアロケーションを抑える
C#で配列を使う際にメモリアロケーションを抑えるテクニックを3つ紹介します。
stackalloc
stackallocを使うとヒープではなくスタックに載る配列を使えます。スタック上ならほとんどノーコストで使えます。
newの代わりにstackallocを使って確保し、Span型の変数に入れます。
Span<int> array = stackalloc int[10];
array[0] = 10;
スタック専用なのでclassやstructのフィールドには持てません。メソッド内のローカル変数として使います。より詳しい制限事項はref構造体の説明を見てください。
Unityでは2021.2から標準で使えます。それ以前のバージョンではSpanが存在しないのでSystem.Memory.dllを入れると使えるようになります。
オブジェクトプール
配列に限らず、ObjectPoolパターンを使えばメモリ確保の頻度を減らせます。特に配列では.NET標準でSystem.Buffers.ArrayPoolが用意されています。
ArrayPool.Shared.Rentで配列を取得し、使い終わったらArrayPool.Shared.Returnで返却します。すぐに返さなくてもいいのでStart()で取得してOnDestory()で返却することもできます。
const int arraySize = 10;
int[] array = ArrayPool<int>.Shared.Rent(arraySize);
array[0] = 10;
// 使い終わったら
ArrayPool<int>.Shared.Return(array);
配列の要素は0初期化されていないことがあるので注意してください。
また、配列のサイズも2の累乗になります。上のサンプルコードではサイズ10で取得していますが、取得された配列のサイズは16になっています。Lengthを取ったりforeachで扱うときには注意が必要です。
Frugal Object
FrugalObjectは要素が少ない内はstructのフィールドとして持っておき、要素が増えてからメモリ確保するパターンです。
次のサンプルコードでは、初めてAddされたときはフィールドのfirstに入れておき、2回目以降はlistにAddしています。こうすることで要素数が1つだけならメモリアロケーションは発生しません。
要素数1で済むことが多い箇所で使えばメモリアロケーションを減らせます。
public struct ListOfOftenOne<T>
{
private int count;
private T first;
private List<T> list;
public void Add(T value)
{
if (count == 0)
{
first = value;
}
else
{
InitializeList();
list.Add(value);
}
++count;
}
public T Get(int index)
{
if (count < 0 || count <= index)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (index == 0)
{
return first;
}
return list[index - 1];
}
private void InitializeList()
{
list ??= new List<T>();
}
}
このサンプルは非常に簡単なものになっていますが、ちゃんとした実装はListOfOftenOneやCompactListがわかりやすいです。
実装次第で3つまでアロケーションしないようにしたり、ListではなくDictionaryとして使ったりなど応用が利きます。
Hi! Would you mind if I share your blog with my facebook group?
There’s a lot of folks that I think would really enjoy your content.
Please let me know. Thanks
Great article. I will be facing many of these issues
as well..
Hey there! I just wanted to let you know that I’ve got some digital assets available for purchase on my Fiverr profile.
You can head on over to my profile and check out my portfolio to
see if there’s anything that catches your eye. Don’t hesitate to reach out if you have any questions or if you’re interested in placing
an order. Thanks for stopping by! source link: fiverr.com/cpggarud2002
I have been surfing on-line more than 3 hours as of late,
but I never discovered any attention-grabbing article like yours.
It’s lovely price sufficient for me. In my opinion, if all web owners and bloggers made just right content as you did, the web shall be much more helpful than ever before.
A motivating discussion is worth comment. I think that you ought to publish more about this subject, it may
not be a taboo matter but typically people don’t discuss these topics.
To the next! Best wishes!!
I’ll immediately seize your rss as I can’t in finding your e-mail subscription link
or newsletter service. Do you have any? Please let me understand so that I could subscribe.
Thanks.
If you desire to increase your experience simply keep visiting this
web page and be updated with the latest gossip posted here.
I pay a quick visit every day a few web pages and blogs to read content,
however this webpage gives feature based posts.
Howdy would you mind letting me know which hosting company you’re
working with? I’ve loaded your blog in 3 completely different browsers and
I must say this blog loads a lot faster then most.
Can you recommend a good web hosting provider
at a honest price? Kudos, I appreciate it!
I’d like to thank you for the efforts you have
put in writing this site. I really hope to check out the same high-grade content from you in the future as well.
In fact, your creative writing abilities has inspired me
to get my own website now 😉
Hey there superb website! Does running a blog similar to this require a
great deal of work? I have no knowledge of coding but I had been hoping to start my own blog soon.
Anyhow, if you have any suggestions or techniques for new blog owners please share.
I know this is off subject nevertheless I just needed
to ask. Cheers!
This is a topic that’s close to my heart…
Take care! Exactly where are your contact details though?
ngentot
Hi there! Someone in my Facebook group shared this website with us so I came
to take a look. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to
my followers! Great blog and wonderful design.
Here is my website KS Global Ready Mix
Nice post bro dedy07
Hey are using WordPress for your site platform? I’m new to the blog world but I’m trying to get
started and create my own. Do you require any html coding knowledge to make your own blog?
Any help would be really appreciated!
Also visit my homepage :: Jayamix
It’ѕ amazing to pay a visit tһіs website and
reading thhe views οf all colleagues on the topic
of tһis piece of writing, ѡhile I am alѕo zealous of geyting
familiarity.
Check ouut mʏ web page :: Swingers Lifestyle
My spouse and I stumbled over here by a different page and thought I might as
well check things out. I like what I see so i am just following you.
Look forward to finding out about your web page repeatedly.
Also visit my page; Pagar Panel Beton
Hmm it seems like your site ate my first
comment (it was super long) so I guess I’ll just sum it up what I
submitted and say, I’m thoroughly enjoying your blog.
I as well am an aspiring blog writer but I’m still new to the whole thing.
Do you have any points for inexperienced blog writers?
I’d genuinely appreciate it.
Look at my page – U Ditch Precast