Tecky‘s Blog

你拍一、我拍一,喝着茅台吹牛逼
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用不安全代码在栈上创建和使用数组

Posted on 2011-02-09 15:16  Tecky Li  阅读(539)  评论(0)    收藏  举报

数组是类对象,存储空间在堆上,是一种引用类型。那么如何在栈上创建和访问数组元素以获得更高的效率那?下面是CLR Via C#中给出的一段示例代码,分别使用stackalloc 和创建结构类型实例来实现在栈上使用数组。

 

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];  
}
 
在上面的InlineArrayDemo函数中,结构类型实例肯定是在栈上分配空间的,所以在CharArray结构体中内置一个Char数组的话,这个Char数组也会被分配到栈上。
这两种方法都是用不安全的代码,在使用的时候需要慎重。