Home Backend Development C#.Net Tutorial C# basic memory allocation

C# basic memory allocation

Feb 07, 2017 pm 03:52 PM
c# memory allocation

1. Create an object


The creation process of an object is mainly divided into two parts: memory allocation and initialization. In .NET, the memory area managed by CLR mainly consists of three parts: stack, GC heap, and LOH heap. The stack is mainly used to allocate value type data. Its management is controlled by the system, not by the GC like the GC heap. When the thread finishes executing the method of the value type instance, this space will be automatically released. Generally, the stack has high execution efficiency but limited capacity.

The GC heap is used to allocate small object instances. It is fully controlled by the GC to allocate and recycle memory. The LOH heap is prepared for large object instances. It will not be compressed and will only be recycled when the GC is fully recycled. In IL, you can see common instructions for creating objects such as newobj, ldstr (creating string objects), newarr (used to allocate new array objects), box (boxing), etc.

Of course, value types also exist on the heap. For example, when a value type is used as a field of a class, it will be stored in the instance object space in the heap, and when boxing, the value type will also exist on the heap. Okay, let's take a look at the memory allocation of creating an object. Now there is a Person class and Student class. Then this sentence Student s = new Student() { studentId = 2, Id = 4 }; After execution, the s object is created. Below I draw a picture to illustrate the memory allocation when creating an object, in which the s object also There are synchronized index blocks and type object pointers that I didn't draw.

public class Person
    {
        public int Id;
        public void Eat()
        {
            Console.WriteLine("Eat Pear");
        }
    }
 
    public class Student:Person
    {
        public int studentId;
        public void GotoSchool()
        {
            Console.WriteLine("Go to School");
        }
    }
Copy after login

View Code

C# basic memory allocation


2. The parent class object points to the subclass

We are writing In order to achieve polymorphism in programs, parent class objects are generally used to point to subclasses. Then when I write Person p=new Student();, a subclass object is created in the heap. The following is the memory allocation diagram of the parent class object pointing to the subclass. I added virtual methods and abstract methods in Person and overridden methods in Student subclass.

It can be seen from the figure that once the subclass overrides the virtual method or abstract method of the parent class, the two methods in the Person method table will be overridden by the subclass, and we can implement polymorphism based on it. . In addition, there is a new void Eat() method in the Student method table, but it cannot be called by p because new Eat() at this time belongs to a subclass.

That is to say, except for the overridden methods, p can only call methods in the Person method table. If it cannot be found, it will continue to search for methods of the Person parent class until object. Note that it will not look back, it will not look for methods in the Student method table

public  abstract class Person
    {
        public  int Id;
        public void Eat()
        {
            Console.WriteLine( "在吃梨");
        }
        public virtual void Walk()
        {
            Console.WriteLine("在散步");
        }
        //抽象方法只能在抽象类中声明,因此要在Person前加abstract,且只能声明并必须在子类中实现。
        public abstract void Run();
    }

public class Student:Person
    {
        public int studentId;
        public void GotoSchool()
        {
            Console.WriteLine("Go to School");
        }
 
        public new void Eat()
        {
            Console.WriteLine("学生  吃苹果");
        }
        public override void Walk()
        {
            Console.WriteLine("学生  在散步");
        }
        public override void Run()
        {
            Console.WriteLine("学生  在跑步");
        }
    }
Copy after login

C# basic memory allocation

3. Point to the grandchild object

Now I will Add a Student subclass James. From the previous example, we already know that only the methods overridden by the override keyword will be called by the parent class, so I deleted all ordinary methods. The execution code is Person p = new James() { name = “James”, studentId = 2, Id = 4 }; The code and memory allocation diagram are as follows. In order to highlight the key points, I have not drawn the fields in the diagram. From the results, we can see that the SayHi method was finally overwritten by the SayHi of the grandchild class. From here, we can see the transitivity of inheritance!

public  abstract class Person
    {
        public  int Id;
        public virtual void Eat()
        {
            Console.WriteLine( "在吃梨");
        }
        public virtual void Walk()
        {
            Console.WriteLine("在散步");
        }
        //抽象方法只能在抽象类中声明,因此要在Person前加abstract,且只能声明并必须在子类中实现。
        public abstract void Run();
        public virtual void SayHi()
        {
            Console.WriteLine("人说:你好!");
        }
    }

public class Student:Person
    {
        public int studentId;
        public virtual void Eat()
        {
            Console.WriteLine("学生  在吃梨");
        }
        public override void Walk()
        {
            Console.WriteLine("学生  在散步");
        }
        public override void Run()
        {
            Console.WriteLine("学生  在跑步");
        }
    }

public class James:Student
    {
        public string name;
        public override void Eat()
        {
            Console.WriteLine("James  在吃梨");
        }
        public override void Walk()
        {
            Console.WriteLine("James  在散步");
        }
        public override void Run()
        {
            Console.WriteLine("James  在跑步");
        }
        public override  void SayHi()
        {
            Console.WriteLine("James说:你好!");
        }
    }
Copy after login

C# basic memory allocation

The above is the content of C# basic memory allocation. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

See all articles