C#编程(七十六)----------使用指针实现基于栈的高性能数组

使用指针实现基于栈的高性能数组

以一个案例为主来分析实现方法:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace 基于堆栈的数组

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] i = new int[10];

            Console.WriteLine(i[1]);   

            /*使用指针优化性能

             使用关键字stackalloc创建基于堆栈的高效数组

             */

            unsafe

            {

                /*

                 * stackalloc命令只分配堆栈内存而已,不会把内存初始化为任何默认值

                 * 1.其后紧跟要存储数据类型名(该数据类型必须是值类型)

                 * 2.分配的字节数为变量个数*sizeof(数据类型)

                 */

                int* pInt = stackalloc int[10];

                *pInt = 0;

                *(pInt + 1) = 1;

                pInt[2] = 5;        //表达式被编译为*(pInt+2)

                pInt[50] = 100;     //不会报错,使用stackalloc声明相同数组,对数组边界检查,该数组黑没有封装任何对象

                Console.WriteLine(*(pInt+1));

                Console.WriteLine(pInt[2]);

                Console.WriteLine(*(pInt+3));

                Console.WriteLine(pInt[50]);

                Console.ReadKey();

            }

            

        }

    }

}

原文地址:https://www.cnblogs.com/android-blogs/p/6638966.html