Php5.2 memory manager

Source: Internet
Author: User
Tags mysql functions php windows ibm developerworks
Php5.2 memory manager? New features in PHPV5.2, Part 1: use the new memory manager to track and monitor PHP memory TracyPeterson (tracy@tracypeterson.com) like uber-nerd, freelance writer, Consultan php 1st memory manager

?

New features in PHP V5.2, Part 1: Use the new memory manager

Tracking and monitoring PHP memory like tracking and monitoring uber-nerd

Tracy Peterson (tracy@tracypeterson.com), freelance writer, Consultant has been an IT project manager and Web developer since 1997, and is currently the computing director of Microsoft's MSN Search. He is currently working in San Francisco.

Introduction:? Learn how to use the new memory manager introduced in PHP V5.2 and become proficient in tracking and monitoring memory usage. This allows you to use more memory more effectively in PHP V5.2.

View more content in this series

Mark this article!

Release date:? April 10, 2007
Level:? Intermediate
Access Status? 1145 views
Suggestion:? 0? (Add comments)

Average score (2 in total)

PHP V5.2: start

PHP V5.2 was released in November 2006, which includes many new features and error fixes. It abolished version 5.1 and is recommended to all PHP V5 users for upgrade. My favorite lab environment-Windows? , Apache, MySQL, PHP (WAMP) -- has been introduced into the new software package V5.2 (see references ). Where do you find Windows? Install PHP V5.2, MySQL, and Apache applications on an XP or 2003 computer. You can install it easily. it has many minor management advantages, and I sincerely recommend it.

Although this is the simplest software package for Windows users, you need to add the following code when configuring PHP on Linux:--memory-limit-enabled(Except for any other options on your server ). However, in Windows, a function is provided to solve this problem.

PHP V5.2 has many improvements and a crucial area is memory management. Accurately quoted from README. ZEND_MM: "The goal of the new memory manager (PHP5.2 and later) is to reduce memory allocation overhead and accelerate memory management ."

The following are some key content in the V5.2 release notes:

  • Unnecessary--disable-zend-memory-managerConfiguration options
  • Added--enable-malloc-mmConfiguration option. this configuration option is enabled by default during build debugging to allow the use of internal and external memory debugging programs
  • AllowedZEND_MM_MEM_TYPEAndZEND_MM_SEG_SIZEEnvironment variable adjustment memory manager

To understand the meaning of these new features, we need to study the art of memory management in depth and consider why allocating overhead and running speed are a big problem.

Back to top

Why memory management?

One of the fastest developing technologies in computing is memory and data storage, which are driven by the continuous demand for increasing speed and storage size. Early computers used cards as memory and switched to chip technology. Can you imagine that a computer with only 1 kb ram memory works? Many early computer programmers have used it. These pioneers soon realized that to work under technical restrictions, they would have to carefully use trivial commands to avoid system overload.

As a PHP developer, our environment is easier to code than our colleagues who use C ++ or other more rigorous language encoding. In our world, we don't have to worry about how to handle system memory, because PHP will handle this problem for us. However, in other programming fields, responsible coding personnel will use various functions to ensure that the executed commands do not overwrite other program data-thus, undermining the running of the program.

Memory management is usually handled by self-coding personnel requests to allocate and release memory blocks.Allocate blocksIt can save any type of data, and this process will separate a certain amount of memory for the data, and provide the access method for the application when the operation needs to access the data. People expect the program to release the allocated memory after any operation and allow the system and other programmers to use the memory. If the program does not release the memory back to the system, it is calledMemory leakage.

Leakage is a common problem in any running program, and is generally acceptable to some extent, especially when we know that the running program will immediately terminate and release all the memory allocated to the program by default.

It is a problem because the program is run and terminated randomly, just like almost all client applications. It is expected that the server application runs uncertain without terminating or restarting, which makes memory management absolutely crucial for server daemon programming. In a program that runs for a long time, even if a small leak occurs, the system will eventually become weak because the memory block has been used and will never be released.

Back to top

Long-term considerations

Like writing in any language, permanent server daemon written in PHP has many possibilities. But when we start using PHP for these purposes, we must also consider memory usage.

Scripts that parse a large amount of data or may hide infinite loops tend to consume a large amount of memory. Obviously, once the memory is exhausted, the server performance will be reduced. Therefore, we must pay attention to the memory usage when executing the script. Although we can simply observe the memory usage by enabling the system monitor, it does not tell us anything more useful than the overall system memory status. Sometimes we don't just need to help with troubleshooting or optimization, but sometimes we just need more details.

One way to get the transparency of script execution content is to use an internal or external debugger.Internal debuggerIs the same process as the script execution. From the operating system perspective, the independent process isExternal debugger. Memory analysis using the debugger is similar to any situation, but different methods are used to access the memory. The internal debugger has direct access to the memory space of the running process, and the external debugger accesses the memory through sockets.

There are many methods and available debugging servers (external) and libraries (internal) that can be used for auxiliary development. You can use the newly provided--enable-malloc-mmInDEBUGThe build is enabled by default. This makes the environment variableUSE_ZEND_ALLOCCan be used to allow selection at runtimeMallocOrEmallocMemory allocation. The use of malloc-type memory allocation will allow the external debugger to observe the memory usage, and the emalloc allocation will use the Zend memory manager abstraction, requiring internal debugging.

Back to top

Memory management functions in PHP

In addition to making the memory manager more flexible and transparent, PHP V5.2 alsomemory_get_usage()Andmemory_get_peak_usage()A new parameter is provided, which allows you to view memory usage. The new boolean value mentioned in the description isreal_size. Call a functionmemory_get_usage($real);(Where$real = true), The result is the actual memory size allocated by the system during the call, including the memory manager overhead. If no tag Group is used, the returned data will only include the memory used in the running script, minus the memory manager overhead.

memory_get_usage()Andmemory_get_peak_usage()The difference is that the latter will return the maximum memory size of the running process called so far, while the former will only return the usage during execution.

Formemory_get_usage(), Php.net provides code snippets in listing 1.


Listing 1.memory_get_usage()Example
                
     

In this simple example, we first callmemory_get_usage()The code comment shows 36640 bytes of common results in the author's system. Then we use 4,242 "Hello" copies for loading.$aAnd run the function again. Figure 1 shows the output of this simple application.


Figure 1.memory_get_usage()Sample output


Nomemory_get_peak_usage()Because the two are very similar, the syntax is the same. However, the sample code in listing 1 has only one result, that is, the maximum memory usage at that time. Let's take a look at listing 2.


List 2.memory_get_peak_usage()Example
                
     

The code in listing 2 is the same as that in figure 1,memory_get_usage()Already replacedmemory_get_peak_usage(). Fill in with 4242 "Hello" copies.$aPreviously, the output won't be much changed. Memory jumps to 57960, indicating the peak value so far. When we check the peak memory usage, we get the maximum value so far, so all further calls will get 57960 until we process the operation ratio.$aMore memory is used (see figure 2 ).


Figure 2.memory_get_peak_usage()Sample output


Back to top

Restrict memory usage

One way to ensure that the servers hosting applications are not overloaded is to limit the amount of memory used by any scripts executed by PHP. This is not the operation we should perform, but because PHP is a loose language and parsed at runtime, therefore, we sometimes get a script that is poorly written after being released to the production application. These scripts may execute loops or open a long file list. if you forget to close the current file before opening a new file. In either case, poorly written scripts may end up consuming a lot of memory before you know it.

In PHP. INI, you can use configuration parametersmemory_limitTo specify the maximum memory usage that any script can run in the system. This is not a specific change to V5.2, but the memory manager and any discussions on its use are worth viewing this feature at least once. It also carefully guides me through the last few new features of the memory manager: environment variables.

Back to top

Adjust memory manager

Finally, how can we program without being a perfectionist but completely serving our purposes? New environment variableZEND_MM_MEM_TYPEAndZEND_MM_SEG_SIZEIt can meet your needs.

When the memory manager allocates large memory blocks, it is installedZEND_MM_SEG_SIZEVariable. The default partition size of these memory blocks is 256 KB, but you can adjust the partition size to meet special requirements. For example, if you notice that the operation in the most common script causes a large amount of memory waste, you can adjust this size to a value closer to match the script requirement, the amount of allocated memory is reduced, but the remaining amount of memory is still zero. Under the correct conditions, such careful configuration adjustment may cause a huge difference.

Back to top

Retrieve memory usage in Windows

If you have pre-built PHP Windows binary code that is not used during build--enable-memory-limitOption, you need to browse this part before continuing. For Linux ?, Used to configure PHP build--enable-memory-limitOption to build PHP.

To use Windows binary code to retrieve memory usage, create the following functions.


Listing 3. Getting memory usage in Windows
                
     

Save the result to a file named function. php. Now you can only include this file in the script that requires it.

Back to top

Practice

Let's take a look at the benefits of using the actual examples of these settings. You may wonder why the memory is not allocated properly at the end of the script many times. The reason is that some functions cause memory leakage, especially when only built-in PHP functions are used. Here, you will learn how to discover such problems. To start the memory leak search, you will create a MySQL database, as shown in listing 4.


Listing 4. creating a test database
                mysql> create database memory_test;mysql> use memory_test;mysql> create table leak_test       ( id int not null primary key auto_increment,         data varchar(255) not null default '');mysql> insert into leak_test (data) values ("data1"),("data 2"),       ("data 3"),("data 4"),("data 5"),("data6"),("data 7"),       ("data 8"),("data 9"),("data 10");

This creates a simple table with the ID field and data field.

In the next list, imagine that our tough programmer is executing some MySQL functions, especially when usingmysql_query()Apply the result to a variable. When he does this, he will notice that even ifmysql_free_result(), Some memory will not be released, resulting in memory usage increasing with the Apache process (see listing 5 ).


Listing 5. Examples of memory leakage detection
                for ( $x=0; $x<300; $x++ ) {    $db = mysql_connect("localhost", "root", "test");    mysql_select_db("test");    $sql  = "SELECT data FROM test";     $result = mysql_query($sql); // The operation suspected of leaking    mysql_free_result($result);    mysql_close($db); }

Listing 5 is a simple MySQL database operation that can be used anywhere. When running the script, we noticed some strange behaviors related to memory usage and need to check them out. To use the memory management function so that we can check the location where an error occurs, we will use the following code.


Listing 6. Examples of calibration lookup errors
                
     ";    $db = mysql_connect("localhost", "user", "password");mysql_select_db("memory_test");echo "After connecting, we're using (in bytes): ",     memory_get_usage(),"\n
"; for ( $x=0; $x<10; $x++ ) { $sql = "SELECT data FROM leak_test WHERE id='".$x."'"; $result = mysql_query($sql); // The operation // suspected of leaking. echo "After query #$x, we're using (in bytes): ", memory_get_usage(), "\n
"; mysql_free_result($result); echo "After freeing result $x, we're using (in bytes): ", memory_get_usage(), "\n
";} mysql_close($db);echo "After closing the connection, we're using (in bytes): ", memory_get_usage(), "\n
";echo "Peak memory usage for the script (in bytes):". memory_get_peak_usage();?>

Note: Check the current memory usage according to the defined interval. In the following output, we show that our script has been allocating memory for the function, and the memory should not be released at the time of release, so as to provide a practical test of memory leakage, you can see how memory usage increases during each call.


Listing 7. test script output
                At the start we're using (in bytes): 63216After connecting, we're using (in bytes): 64436After query #0, we're using (in bytes): 64760After freeing result 0, we're using (in bytes): 64828After query #1, we're using (in bytes): 65004After freeing result 1, we're using (in bytes): 65080After query #2, we're using (in bytes): 65160After freeing result 2, we're using (in bytes): 65204After query #3, we're using (in bytes): 65284After freeing result 3, we're using (in bytes): 65328After query #4, we're using (in bytes): 65408After freeing result 4, we're using (in bytes): 65452After query #5, we're using (in bytes): 65532After freeing result 5, we're using (in bytes): 65576After query #6, we're using (in bytes): 65656After freeing result 6, we're using (in bytes): 65700After query #7, we're using (in bytes): 65780After freeing result 7, we're using (in bytes): 65824After query #8, we're using (in bytes): 65904After freeing result 8, we're using (in bytes): 65948After query #9, we're using (in bytes): 66028After freeing result 9, we're using (in bytes): 66072After closing the connection, we're using (in bytes): 65108Peak memory usage for the script (in bytes): 88748

We discovered some suspicious operations when executing the script, and adjusted the script to provide us with some understandable feedback. We ran the script again and used it during each iteration.memory_get_usage()View the changes in memory usage. Based on the increase in the allocated memory value, it implies that we have used scripts to establish a vulnerability somewhere. Becausemysql_free_result()The function does not release the memory, so we can consider thatmysql_query()The memory is not allocated correctly.

Back to top

Conclusion

PHP V5.2 includes some excellent new tools to help you better understand the memory allocation of the script system, and re-control the precise adjustment of memory management. When it is used effectively, the new memory management tool will support debugging and regain some system resources.


References

Learning

  • For more information, see the original article on the developerWorks global site.

  • Read the PHP V5.2 release notes.

  • "How to Manage Memory in PHP" is an excellent article on PHP Memory management programming practices.

  • Zend Developer Zone has many documents for memory manager functions.

  • Access PHP.net to obtain the PHP documentation.

  • Article "A step-by-step how-to guide to install, configure, and test a Linux, Apache, Informix, and PHP server "contains a section about compiling PHP parsing programs for Linux.

  • Check the error reports generated in the actual example.

  • In the "PHP V5 Migration Guide", learn how to migrate the code developed in PHP V4 to V5.

  • To learn how to use PHP for programming, please refer to the "learning PHP" series on developerWorks.

  • Planet PHP is a community news resource for PHP developers.

  • PHP.net is a PHP developer resource.

  • Refer to "PHP recommended books list ".

  • Browse all PHP articles and PHP tutorials on developerWorks.

  • Refer to IBM developerWorks's PHP Project Resource Center extension PHP skills.

  • For interesting interviews and discussions with software developers, visit the developerWorks podcast.

  • Stay tuned to technical events and network broadcasts on developerWorks.

  • Check out recent seminars, trade exhibitions, network broadcasts, and other activities for IBM open source code developers to be held globally.

  • Visit the developerWorks open-source software technology area for a wide range of how-to information, tools, and project updates to help you develop with open source code technology and use it with IBM products.

  • Visit the Safari online bookstore to view various reference materials on open source technology.

Obtain products and technologies

  • Use IBM trial software to build your next development project, which can be downloaded or obtained from a DVD.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.