I am writing a program in C#. Everything centers around a static 2D int array which is 400x6 elements. Just a few values will be updated just once every minute. But after each minute's updates, dozens of functions will read the values millions of times to compute "pattern scores". The faster the calculations, the more distinct functions I can cram in there. Realistically I can allow 30 seconds for this scoring process. Is there a way to allocate the static array to the stack, and if so, would this help the speed? Thanks.
Asked
Active
Viewed 2,272 times
3
-
2There's no reason why it would make any difference. The array is going to be cached anyway. However, there would be a benefit in avoiding bounds checking (using unsafe code). – Luaan Nov 09 '15 at 16:21
2 Answers
4
Yes, you can alloc arrays on the stack in C# using "stackalloc" in "unsafe mode", but benchmarks shows a limited performance gain and the risk is that you hit the 1Mb stack size limit... which will give you a... StackOverflow(tm)!
Here is a good article on the subject: http://blogs.microsoft.co.il/sasha/2013/10/17/on-stackalloc-performance-and-the-large-object-heap/

Dan Byström
- 9,067
- 5
- 38
- 68
-
`stackalloc` can be used with `Span
` and doesn't require "unsafe" context. – Youssef13 Jun 06 '20 at 21:51
0
You can use "stackalloc" to alloc array directly on the stack.
Some documentation about : https://msdn.microsoft.com/en-us/library/aa664785(v=vs.71).aspx
You can also use an implementation of Hamming weight which is describe here : How to allocate arrays on the stack for performance gains?

Community
- 1
- 1

Nicolas HENAUX
- 1,656
- 1
- 14
- 18