zoukankan      html  css  js  c++  java
  • 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();

                }

               

            }

        }

    }

  • 相关阅读:
    netframework webapi IogAttribute记录request参数和错误信息
    An error occurred while starting a transaction on the provider connection. See the inner exception for details.
    mvc partialView断点调试问题
    mysql 用行号rownum更新顺序号字段
    sqlserver 导入excel
    vs2017 git凭证问题
    DataTable 转换为List
    Resharper 修改命名空间
    web api解决序列化后返回标准时间带T问题
    获取当前程序的路径
  • 原文地址:https://www.cnblogs.com/FinleyJiang/p/7606431.html
Copyright © 2011-2022 走看看