Replies: 3 comments 1 reply
-
Moved over to the runtime; the C# language does not care anything about padding or struct sizes. |
Beta Was this translation helpful? Give feedback.
-
After analyzing the JIT x64 assembly of an example C# code, I have reached a conclusionSample C# Codeusing System;
using System.Runtime.CompilerServices;
class Program {
static void Main(){
Test t = default;
t.Index0 = t.Index1 = t.Index2 = t.Index3 = 3;
t.ToString();
//
Buffer<int> b = default;
b[0] = b[1] = b[2] = b[3] = 1;
b.ToString();
}
}
[InlineArray(4)]
public struct Buffer<T> { private T _element0; }
// regular struct
public struct Test { public int Index0, Index1, Index2, Index3; } x64 AssemblyProgram:Main() (FullOpts):
G_M27646_IG01: ;; offset=0x0000
push rbp
mov rbp, rsp
G_M27646_IG02: ;; offset=0x0004
mov rdi, 0x7E64A8804008 ; Test
call CORINFO_HELP_NEWSFAST
mov dword ptr [rax+0x08], 3
mov dword ptr [rax+0x0C], 3
mov dword ptr [rax+0x10], 3
mov dword ptr [rax+0x14], 3
mov rdi, 0x7E6522201578 ; 'Test'
mov esi, 1
call [System.RuntimeType:GetCachedName(int):System.String:this]
mov rdi, 0x7E64A891EAC0 ; Buffer`1[int]
call CORINFO_HELP_NEWSFAST
mov dword ptr [rax+0x08], 1
mov dword ptr [rax+0x0C], 1
mov dword ptr [rax+0x10], 1
mov dword ptr [rax+0x14], 1
mov rdi, 0x7E6522202B50 ; 'Buffer`1[System.Int32]'
mov esi, 1
call [System.RuntimeType:GetCachedName(int):System.String:this]
nop
G_M27646_IG03: ;; offset=0x0085
pop rbp
ret Analysis
Conclusion
|
Beta Was this translation helpful? Give feedback.
-
The elements of regular arrays, inline arrays and stackalloc can be described by the same As for uses of inline arrays, they could be used as a replacement for stackalloc that also allows managed types and more generally if a fixed number of elements is needed (which may not be particularly common). However, exposing an inline array as such in a public API seems unwise because of its weird conversion to span. Also, they interact poorly with collections ( If an inline array is used as a field of a class or other longer-term data structure, it may improve locality and reduce memory consumption slightly (compared to a regular array) but in a way which is hard for compilers to do automatically. For example, if the actual data of the array is small compared to the overhead of an object reference and object header and the number of instances is large. |
Beta Was this translation helpful? Give feedback.
-
Can you confirm whether inline arrays, unlike
stackalloc
, require intra-index padding unless all elements have a 1-byte alignment (e.g.,byte
)? If so, does this mean inline arrays often consume more stack space thanstackalloc
, as they may require padding not just at the beginning or end but also between elements?Additionally, aside from their intended use in P/Invoke scenarios, do inline arrays have significant practical applications?
Thank you in advance for your insights!
Beta Was this translation helpful? Give feedback.
All reactions