An array is a class object, and the storage space is on the stack. It is a reference type. So how to create and access array elements on the stack for higher efficiency? The following is an example of CLR via C #.CodeUse stackalloc and create Schema-type instances to implement the use of arrays on the stack.
Public Static Class Program { Public Static Void Main () {stackallocdemo (); inlinearraydemo ();} Private Static Void Stackallocdemo (){ Unsafe { Const Int32 width = 20; char * Pc = Stackalloc Char [width]; // Allocates array on Stack String S = "Jeffrey Richter" ; // 15 characters For (Int32 Index = 0; index <width; index ++) {PC [width-index-1] = (index <S. Length )? S [Index]: '.' ;} // The line below displays "... rethcir yerffej" Console. writeline ( New String (PC, 0, width ));}} Private Static Void Inlinearraydemo (){Unsafe {Chararray CA; // Allocates array on Stack Int32 widthinbytes = Sizeof (Chararray); int32 width = widthinbytes/2; string S = "Jeffrey Richter" ; // 15 characters For (Int32 Index = 0; index <width; index ++) {ca. characters [width-index-1] = (index <S. Length )? S [Index]: '.' ;} // The line below displays "... rethcir yerffej" Console. writeline ( New String (ca. characters, 0, width ));}}} Internal Unsafe Struct Chararray { // This array is embedded inline inside the structure Public Fixed Char characters [20];}
In the inlinearraydemo function above, the structure type instance must allocate space on the stack. Therefore, if a char array is embedded in the chararray struct, the char array will also be allocated to the stack.
Both methods use Insecure code, so be careful when using them.