Pay attention to memory improvement software performance

zhaozj2021-02-16  59

This article focuses on 2 questions:

1. GC (garbage recycling) problem in C .

2. How to improve the efficiency of memory, improve program performance

I. GC in C

When you create an object in Java, C #, you just need to call New, and you don't need to go to DELETE at all. Because this work is handed over to the mechanism embedded by the language. When an object is not available, it will be Mechanism to achieve garbage collection, return resources to OS tasks. And C is not so lucky. You must be responsible for the use of new, delete to display the resource distribution and resource recycling. Little accidentally I didn't say the seriousness of Memory Leak.Memory Leak. I think something I want to talk about here. I want to talk about several GC realization. Or talking is garbage collection. Just want to do like Java, C # Like the display, only the display is called, without delete, the memory will be released automatically when the object is ended. I want to simulate this idea with relatively simple code.

The most classic is the smart pointer. Or I have a little like a smart pointer. Oh, it is a simple

Then it.

#include

Using namespace std;

Class SMPPOINTER

{

PUBLIC:

SMPPOINTER (Void * P) {_P = P;

}

~ SMPPOINTER () {delete_p;

}

Private:

Void * _P;

}

Class A

{

PUBLIC:

A () {cout << "ctor ();";

}

}

void main ()

{

A * pointer = new a;

SMPPOINTER PTR (Pointer);

}

The above implementation seems to always be a bit unnatural. After calling new, you must allocate a SMPPointer object on the stack. When the program exits (or the function is running), the object on the stack will be destroyed, so you can automatically call SMPPointer. The balanced function is released.

Let's look at the following version. Basic ideas are this: Use a linked list to allocate every object to you, put it down, put it in a linked list. Last unified recycle. When this idea is realized, it must be Reserved New, DELETE operator for each class that needs to be changed. Nor well.

Version 2

#include

#include

Using namespace std;

List memlist; // Assign a two-way linked list of pointers linked to the memory block

Class A

{

PUBLIC:

A () {cout << "ctor a / n";

}

~ A () {cout << "Detor A / N";

}

Void * Operator New (size_t size)

{

Void * p = malloc (size);

Memlist.push_front (p);

Return P;

}

Void Operator Delete (Void * P)

{

Free (p);

}

}

void destroy ()

{

Memlist.clear ();

}

Void fun ()

{

A * pa = new a;

A * pb = new a;

A * pc = new a;

COUT << "Memlist Has:" << Memlist.size () << endl;

DESTROY ();

}

void main ()

{

Fun ();

Cout << "now memlist HAS" << Memlist.size ();

}

转载请注明原文地址:https://www.9cbs.com/read-25181.html

New Post(0)