最新文章 (全部类别)
LinERP - 线联ERP - 表格列头通用弹出菜单
C#统计List<T>字符串属性长度(返回每个属性的最大长度)
网易云音乐ncm转mp3在线转换
NNOMS钮纽OMS系统安装操作手册
线联ERP - 快捷键
LinERP - 线联ERP - 物料管理
线联ERP - 实施与维护事项
线联ERP - 多帐套主数据关系表
线联ERP - 海康威视人脸考勤机设置固定IP、重启设备操作手册
线联ERP用户操作手册 - BOM管理
LinERP - 线联ERP - 公司内部编码客户、供应商对照表
LinERP - 线联ERP试用版下载
LinERP - 线联ERP客户服务
DevExpress V22.1 表格导出PDF支持中文
DevExportTool类 - DevExpress GridView 导出Excel文件通用类
解决DevExpress GridView导出XLS文件报错:Unable to cast object of type 'Windows.Win32.Messageld' to type 'System.IConvertible'
LinERP - 线联ERP - 物料类别操作说明
LinERP - 线联ERP主界面
LinERP - 线联ERP用户操作手册 - 系统登陆
LinERP - 线联ERP - 工具栏按钮列表
LinERP - 线联ERP - 数据查询/数据编辑操作手册
LinERP - 线联ERP - 状态栏操作说明
CMS修改主菜单类别编码CategoryNo
LinERP - 线联ERP简介
明细表支持批量操作删除
C# 图片按钮特效:鼠标移入变浅,移出恢复原样 (ImageButtonHover类)
C# 复制对象属性 CopyProperties扩展方法
线联ERP - 用户操作手册 - 系统初始化
线联ERP - 什么是主账套?
线联ERP - 用户操作手册 - 公司资料设置
C/S快速开发框架旗舰版CSFrameworkV6.0 - VS开发环境配置
修复BUG: CSFramework.EF框架 Remove<T>, RemoveWhere<T>
使用Xlight FTP文件服务器
印章公章在线免费制作
CSFrameworkV6.1旗舰版 - appsettings.json 配置文件增加参数
推荐:使用Photoshop制作ico图标
C#.NET格式化显示:数字末尾不显示0
SQL脚本:更新主表的完成标记FlagFinish=Y
FastReport.NET 设计器汉化&运行时汉化
VS2026/VS2022 关闭 “自动添加 using 命名空间”
C#将List<T>导出为 CSV 文件(Excel 直接打开,无需第三方组件包)
.NET8+EF.Core开发的大型ERP系统客户端4GB电脑测试报告
线联ERP - LinERP HR+考勤系统正式上线
CSFrameworkV6旗舰版 - 复制单据功能
QMS软件简介 | 成本核算报价系统软件简介
QMS - 五金制品行业成本核算报价系统 - 货币资料
QMS - 五金制品行业成本核算报价系统 - 公共字典管理
QMS - 五金制品行业成本核算报价系统 - 物料类别
QMS - 五金制品行业成本核算报价系统 - 物料管理
QMS - 五金制品行业成本核算报价系统 - 图纸文件管理
.net敏捷开发,创造卓越

C#.Net对象内存模型及堆/栈数据结构详解 (二)


C#.Net对象内存模型及堆/栈数据结构详解 (二)


C# Heap(ing) Vs Stack(ing) in .NET: Part II
本文转载http://www.c-sharpcorner.com

Even though with the .NET framework we don''t have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications. Also, having a basic understanding of how memory management works will help explain the behavior of the variables we work with in every program we write. In this article I''ll cover some of the behaviors we need to be aware of when passing parameters to methods.

In Part I we covered the basics of the Heap and Stack functionality and where Variable Types and Reference Types are allocated as our program executes. We also covered the basic idea of what a Pointer is.

Parameters, the Big Picture.

Here''s the detailed view of what happens as our code executes. We covered the basics of what happens when we make a method call in Part I. Let''s get into more detail...

When we make a method call here''s what happens:

  1. Space is allocated for information needed for the execution of our method on the stack (called a Stack Frame). This includes the calling address (a pointer) which is basically a GOTO instruction so when the thread finishes running our method it knows where to go back to in order to continue execution.  
  2. Our method parameters are copied over. This is what we want to look at more closely.
  3. Control is passed to the JIT''ted method and the thread starts executing code. Hence, we have another method represented by a stack frame on the "call stack".

The code:

          public int AddFive(int pValue)
          {
                int result;
                result = pValue + 5;
                return result;

          }

Will make the stack look like this:

NOTE : the method does not live on the stack, and is illustrated here just for reference as the beginnnig of the stack frame.
 
As discussed in Part I, Parameter placement on the stack will be handled differently depending on whether it is a value type or a reference type. A value types is copied over and the reference of a reference type is copied over.ed over.

Passing Value Types.

Here''s the catch with value types...

First, when we are passing a value types, space is allocated and the value in our type is copied to the new space on the stack. Look at the following method:

     class Class1

     {

          public void Go()

          {

              int x = 5;

              AddFive(x);

 

              Console.WriteLine(x.ToString());

              

          }

 

          public int AddFive(int pValue)

          {

              pValue += 5;

              return pValue;

          }

     }

As the method executes, space for "x" is placed on the stack with a value of 5.


 
Next, AddFive() is placed on the stack with space for it''s parameters and the value is copied, bit by bit from x.


 
When AddFive() has finished execution, the thread is passed back to Go() and because AddFive() has completed, pValue is essentially "removed":


 
So it makes sense that the output from our code is "5", right? The point is that any value type parameters passed into a method are carbon copies and we count on the original variable''s value to be preserved.

One thing to keep in mind is that if we have a very large value type (such as a big struct) and pass it to the stack, it can get very expensive in terms of space and processor cycles to copy it over each time. The stack does not have infinite space and just like filling a glass of water from the tap, it can overflow. A struct is a value type that can get pretty big and we have to be aware of how we are handling it.

Here''s a pretty big struct:

           public struct MyStruct

           {

               long a, b, c, d, e, f, g, h, i, j, k, l, m;

           }

Take a look at what happens when we execute Go() and get to the DoSomething() method below:

          public void Go()

          {

             MyStruct x = new MyStruct();

             DoSomething(x);

              

          }

 

 

           public void DoSomething(MyStruct pValue)

           {

                    // DO SOMETHING HERE....

           }

This can be really inefficient. Imaging if we passed the MyStruct a couple thousand times and you can understand how it could really bog things down.

So how do we get around this problem? By passing a reference to the original value type as follows: 

          public void Go()

          {

             MyStruct x = new MyStruct();

             DoSomething(ref x);

              

          }

 

           public struct MyStruct

           {

               long a, b, c, d, e, f, g, h, i, j, k, l, m;

           }

 

           public void DoSomething(ref MyStruct pValue)

           {

                    // DO SOMETHING HERE....

           }

This way we end up with more memory efficient allocation of our objects in memory. 


 
The only thing we have to watch out for when passing our value type by reference is that we have access to the value type''s value. Whatever is changed in pValue is changed in x. Using the code below, our results are going to be "12345" because the pValue.a actually is looking at the memory space where our original x variable was declared.

          public void Go()

          {

             MyStruct x = new MyStruct();

             x.a = 5;

             DoSomething(ref x);

 

             Console.WriteLine(x.a.ToString());

               

          }

 

          public void DoSomething(ref MyStruct pValue)

          {

                   pValue.a = 12345;

          }

Passing Reference Types.

Passing parameters that are reference types is similar to passing value types by reference as in the previous example.

If we are using the value type

           public class MyInt

           {

               public int MyValue;

           }

And call the Go() method, the MyInt ends up on the heap because it is a reference type:

          public void Go()

          {

             MyInt x = new MyInt();              

          }

 

If we execute Go() as in the following code ...

          public void Go()

          {

             MyInt x = new MyInt();

             x.MyValue = 2;

 

             DoSomething(x);

 

             Console.WriteLine(x.MyValue.ToString());

              

          }

 

           public void DoSomething(MyInt pValue)

           {

               pValue.MyValue = 12345;

           }

Here''s what happens...

 

  1.  Starting with the call to Go() the variable x goes on the stack.
  2. Starting with the call to DoSomething() the parameter pValue goes on the stack.
  3. The value of x (the address of MyInt on the stack) is copied to pValue

So it makes sense that when we change the MyValue property of the MyInt object in the heap using pValue and we later refer to the object on the heap using x, we get the value "12345".

So here''s where it gets interesting. What happens when we pass a reference type by reference?

Check it out. If we have a Thing class and Animal and Vegetables are both things:

           public class Thing

           {

           }

 

           public class Animal:Thing

           {

               public int Weight;

           }

 

           public class Vegetable:Thing

           {

               public int Length;

           }

And we execute the Go() method below:

          public void Go()

          {

             Thing x = new Animal();

           

             Switcharoo(ref x);

 

              Console.WriteLine(

                "x is Animal    :   "

                + (x is Animal).ToString());

 

              Console.WriteLine(

                  "x is Vegetable :   "

                  + (x is Vegetable).ToString());

              

          }

 

           public void Switcharoo(ref Thing pValue)

           {

               pValue = new Vegetable();

           }

Our variable x is turned into a Vegetable.

x is Animal    :   False
x is Vegetable :   True

Let''s take a look at what''s happening:

 

  1. Starting with the Go() method call, the x pointer goes on the stack
  2. The Animal goes on the hea
  3. Starting with the call to Switcharoo() method, the pValue goes on the stack and points to x

  4. The Vegetable goes on the heapthe heap
  5. The value of x is changed through pValue to the address of the Vegetable

If we don''t pass the Thing by ref, we''ll keep the Animal and get the opposite results from our code.

If the above code doesn''t make sense, check out my article on types of Reference variables to get a better understanding of how variables work with reference types.

In Conclusion.

We''ve looked at how parameter passing is handled in memory and now know what to look out for. In the next part of this series, we''ll take a look at what happens to reference variables that live in the stack and how to overcome some of the issues we''ll have when copying objects.



本文来源:
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
C/S框架网
上一篇:C#.Net对象内存模型及堆/栈数据结构详解 (一)
下一篇:C#.Net对象内存模型及堆/栈数据结构详解 (三)
评论列表

发表评论

评论内容
昵称:
关联文章

C#.Net对象内存模型/数据结构详解 ()
C#.Net对象内存模型/数据结构详解 (三)
C#.Net对象内存模型/数据结构详解 (一)
C#.Net对象内存模型/数据结构详解 (四)
C#.Net WCF实例详解源码下载
CSFramework代码生成器根据数据库表结构生成实体对象模型C#代码)
C#.NET GC.Collect垃圾回收机制详解
了解溢出StackOverFloweExeption的原理吗?
CSFramework.WebApi用户请求对象模型
C#.NET次开发框架,次开发平台产品介绍-C/S框架网
.NET 6 优先队列 PriorityQueue 详解
DbDataUpdate - 自动提交对象模型数据 - 常用数据类型测试
使用[后台数据更新模型]保存主从表数据(C#源码)
C#.Net窗体多重继承构造器Load事件执行顺序详解
DbFramework数据库实体类对象模型框架( 支持MsSQL,MySQL,Oracle三种数据库)
C#数据转换类ConvertEx,封装.Net的Convert对象
C#.NET 实体框架EF(Entity Framework)详解
CSFramework.DbDataUpdate数据模型框架 - 特殊数据类型测试报告
Winform C/S结构与Web B/S结构开发MES/ERP系统优缺点区别
FastReport.NET2023报表数据源配置详解

热门标签
软件著作权登记证书 .NET .NET Reactor .NET5 .NET6 .NET7 .NET8 .NET9 .NETFramework AI编程 APP AspNetCore AuthV3 Auth-软件授权注册系统 Axios B/S B/S开发框架 B/S框架 BSFramework Bug Bug记录 C#加密解密 C#源码 C/S CHATGPT CMS系统 CodeGenerator CSFramework.DB CSFramework.EF CSFramework.License CSFrameworkV1学习版 CSFrameworkV2标准版 CSFrameworkV3高级版 CSFrameworkV4企业版 CSFrameworkV5旗舰版 CSFrameworkV6.0 CSFrameworkV6.1 CSFrameworkV6旗舰版 DAL数据访问层 DaMeng Database datalock DbFramework DeepSeek Demo教学 Demo实例 Demo下载 DevExpress教程 Docker Desktop DOM ECS服务器 EFCore EF框架 Element-UI EntityFramework ERP ES6 Excel FastReport GIT HR HR考勤系统 IDatabase IIS JavaScript LinERP LINQ MES MiniFramework MIS MSSQL MySql NavBarControl NETCore Node.JS NPM OMS Oracle资料 ORM PaaS POS PostgreSql Promise API PSD QMS RedGet Redis RSA SAP Schema SEO SEO文章 SQL SQLConnector SQLite SqlServer Swagger TMS系统 Token令牌 VS2022 VSCode VS升级 VUE WCF WebApi WebApi NETCore WebApi框架 WEB开发框架 Windows服务 Winform 开发框架 Winform 开发平台 WinFramework Workflow工作流 Workflow流程引擎 XtraReport 安装环境 版本区别 报表 备份还原 踩坑日记 操作手册 成本核算系统 达梦数据库 代码生成器 电子线材ERP 迭代开发记录 功能介绍 官方软件下载 国际化 海康威视考勤 基础资料窗体 架构设计 角色权限 开发sce 开发工具 开发技巧 开发教程 开发框架 开发平台 开发指南 客户案例 快速搭站系统 快速开发平台 框架升级 毛衫行业ERP 秘钥 密钥 企业网络维护 权限设计 软件报价 软件测试报告 软件加壳 软件简介 软件开发框架 软件开发平台 软件开发文档 软件授权 软件授权注册系统 软件体系架构 软件下载 软件著作权登记证书 软著证书 三层架构 设计模式 生成代码 实用小技巧 视频下载 收钱音箱 数据锁 数据同步 塑木地板行业ERP 推荐软件 微信小程序 未解决问题 文档下载 喜鹊ERP 喜鹊软件 系统对接 线联ERP 详细设计说明书 新功能 信创 行政区域数据库 需求分析 疑难杂症 蝇量级框架 蝇量框架 用户管理 用户开发手册 用户控件 在线软件 在线支付 纸箱ERP 智能语音收款机 自定义窗体 自定义组件 自动升级程序
联系我们
联系电话:13923396219(微信同号)
电子邮箱:23404761@qq.com
站长微信二维码
微信二维码