search
HomeBackend DevelopmentPHP TutorialWill PHP's unset release memory?_PHP Tutorial

Will PHP's unset release memory?_PHP Tutorial

Jul 20, 2016 am 11:13 AM
dumpgetmemoryphpunsetvarexampleMemoryusoflookafter allfreed

First let us look at an example

var_dump(memory_get_usage());
$a = "laruence";
var_dump(memory_get_usage());
unset( $a);
var_dump(memory_get_usage());

Output (on my personal computer, it may vary depending on the system, PHP version, and loaded extensions):

int(90440)
int(90640)
int(90472

Notice that 90472-90440=32, so there are various conclusions. Some people say that PHP’s unset is not It does not really release memory. Some say that PHP's unset only truly frees memory when it releases large variables (a large number of strings and large arrays). Some even say that it is meaningless to discuss memory at the PHP level.

So, will unset release memory? Where do these 32 bytes go?

To answer this question, I will start from two aspects:
These 32 bytes Where did it go?

First of all, we have to break a thought: PHP is not like the C language. Memory allocation will occur only if you explicitly call the memory allocation related API.
In other words, in PHP, There are many memory allocation processes that we cannot see.
For example:

$a = "laruence";

The implicit memory allocation point is:

1. Allocate memory for the variable name and store it in the symbol table
2. Allocate memory for the variable value

So, you can’t just look at the appearance.
Second, don’t doubt that PHP’s unset will indeed Release the memory (of course, it must be combined with references and counting. For this part, please refer to my previous article on in-depth understanding of PHP principles of variable separation/reference), but this release is not a release in the sense of C programming, and it is not handed back to the OS.
For PHP, it provides a set of memory management APIs similar to the C language for memory allocation. These APIs correspond to the meanings of C APIs. Memory is managed internally in PHP through these APIs.

When we call emalloc to apply for memory, PHP does not simply ask the OS for memory, but asks the OS for a large block of memory, and then allocates a piece of it to the applicant, so that there is logic When applying for memory, you no longer need to apply for memory from the OS, avoiding frequent system calls.

For example, the following example:

var_dump(memory_get_usage (TRUE)); //Note that what is obtained is real_size
$a = "laruence";
var_dump(memory_get_usage(TRUE));
unset($a);
var_dump(memory_get_usage(TRUE) ));

Output:

int(262144)
int(262144)
int(262144

That is when we define the variable $a , PHP did not apply for new memory from the system.

Same as In this way, when we call efree to release memory, PHP will not return the memory to the OS, but will add this memory to the free memory list it maintains. For small pieces of memory, More likely, put it in the memory cache list (postscript, some versions of PHP, such as PHP5.2.4, 5.2.6, 5.2.8, which I verified, When calling get_memory_usage(), the available memory block size in the memory cache list will not be subtracted, causing it to appear that the memory remains unchanged after unset).

Now let me answer this 32-byte run Where did it go? As I just said, many memory allocation processes are not explicit. You will understand after reading the following code:

var_dump("I am www .7di.net");
var_dump(memory_get_usage());
$a = "laruence";
var_dump(memory_get_usage());
unset($a);
var_dump (memory_get_usage());

Output:

string(43) "I am www.7di.net"
int(90808) //Before assignment
int(90976 )
int(90808) //Yes, the memory is released normally

90808-90808 = 0, which is normal, that is to say, these 32 bytes are occupied by the output function (strictly speaking , is occupied by the output Header)


An array that only increases but never decreases

Hashtable is the core structure of PHP (to understand Hashtable, you can refer to my previous article for an in-depth understanding of PHP Array (traversal order)), the array is also represented by her, and the symbol table is also an associative array, for the following code:

var_dump("I am www.7di.net");
var_dump(memory_get_usage());
$array = array_fill(1, 100, "laruence");
foreach ($array as $key => $value) {
${$value . $ key} = NULL;
}
var_dump(memory_get_usage());
foreach ($array as $key=> $value) {
unset(${$value . $key}) ;
}
var_dump(memory_get_usage());

We defined 100 variables, and then clicked Unset to see the output:

string(43) "I am www.7di.net"
int(93560)
int (118848)
int(104448

Wow, why is there so much less memory?
This is because for Hashtable, when defining it, it is impossible to allocate enough memory blocks at one time , to save an unknown number of elements, so PHP will only allocate a small part of the memory block to HashTable during initialization, and then RESIZE to expand the capacity when it is not enough,

And Hashtable, It can only expand the capacity, not reduce it. For the above example, when we stored 100 variables, the symbol table was not enough, so we did an expansion. When we unset these 100 variables in sequence, the memory occupied by the variables is released (118848 – 104448), but the symbol table is not reduced. So the small amount of memory is occupied by the symbol table itself...

Now, do you have a preliminary understanding of PHP's memory management?

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440396.htmlTechArticleFirst let us look at an example var_dump(memory_get_usage()); $a = "laruence"; var_dump(memory_get_usage( )); unset($a); var_dump(memory_get_usage()); output(on my PC...
Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software