Home Backend Development PHP Tutorial PHP array memory usage analysis

PHP array memory usage analysis

Dec 09, 2019 pm 05:54 PM
php array

How much memory will the following approach take up?

list($appid,$openid) = ["testcontent","test"];
Copy after login

Test

$m0 = memory_get_usage();
$k = range(1,200000);
$m1 = memory_get_usage();
echo round(($m1-$m0)/pow(1024,2),4) ."MB\n";
foreach ($k as $i){
    $n1 = "kk$i";
    $n2 = "tt$i";
    list($$n1,$$n2) = [$i,$i*3];
}
$m2 = memory_get_usage();
echo round(($m2-$m1)/pow(1024,2),4) ."MB\n";
$m1 = memory_get_usage();
foreach ($k as $i){
    $n1 = "kk$i";
    $n2 = "tt$i";
    $$n1 = $i+time();
    $$n2 = 2*time();
}
$m2 = memory_get_usage();
echo round(($m2-$m1)/pow(1024,2),4) ."MB\n";
Copy after login

The results of the above operation output are as follows:

27.9404MB
51.3041MB
9.1553MB
Copy after login

It can be seen that the memory occupied by the array is much larger than the normally allocated content

Principle

In PHP, the long type is used to represent numbers, and the int type is not used. Everyone understands that PHP is a weakly typed language. It does not distinguish the type of variables and has no concepts such as int float char *. Let's take a look at the variables PHP stores in zend. Each variable in PHP has a corresponding zval. The Zval structure is defined in Zend/zend.h. Its structure:

typedef struct _zval_struct zval;  
struct _zval_struct {  
    /* Variable information */  
    zvalue_value value;     /* The value 1 12字节(32位机是12,64位机需要8+4+4=16) */  
    zend_uint refcount__gc; /* The number of references to this value (for GC) 4字节 */  
    zend_uchar type;        /* The active type 1字节*/  
    zend_uchar is_ref__gc;  /* Whether this value is a reference (&) 1字节*/  
};
Copy after login

PHP uses a UNION structure To store the value of the variable, that is, zvalue_value is a union. The memory occupied by the UNION variable is determined by the maximum member data space.

typedef union _zvalue_value {  
    long lval;                  /* long value */  
    double dval;                /* double value */  
    struct {                    /* string value */  
        char *val;  
        int len;  
    } str;   
    HashTable *ht;              /* hash table value */  
    zend_object_value obj;      /*object value */  
} zvalue_value;
Copy after login

The largest member data space is struct str, the pointer occupies 4 bytes for *val, and INT occupies 4 bytes, for a total of 8 bytes.

The space occupied by struct zval is 8 4 1 1 = 14 bytes. In fact, arrays, strings and objects in zval require additional storage structures. The array is a HashTable:

The HashTable structure is defined in Zend/zend_hash.h.

typedef struct _hashtable {  
    uint nTableSize;//4  
    uint nTableMask;//4  
    uint nNumOfElements;//4  
    ulong nNextFreeElement;//4  
    Bucket *pInternalPointer;   /* Used for element traversal 4*/  
    Bucket *pListHead;//4  
    Bucket *pListTail;//4  
    Bucket **arBuckets;//4  
    dtor_func_t pDestructor;//4  
    zend_bool persistent;//1  
    unsigned char nApplyCount;//1  
    zend_bool bApplyProtection;//1  
#if ZEND_DEBUG  
    int inconsistent;//4  
#endif  
} HashTable;
Copy after login

The HashTable structure requires 39 bytes, and each array element is stored in the Bucket structure:

typedef struct bucket {  
    ulong h;    /* Used for numeric indexing                4字节 */  
    uint nKeyLength;    /* The length of the key (for string keys)  4字节 */  
    void *pData;        /* 4字节*/  
    void *pDataPtr;         /* 4字节*/  
    struct bucket *pListNext;  /* PHP arrays are ordered. This gives the next element in that order4字节*/  
    struct bucket *pListLast;  /* and this gives the previous element           4字节 */  
    struct bucket *pNext;      /* The next element in this (doubly) linked list     4字节*/  
    struct bucket *pLast;      /* The previous element in this (doubly) linked list     4字节*/  
    char arKey[1];            /* Must be last element   1字节*/  
} Bucket;
Copy after login

The Bucket structure requires 33 Bytes, the part with a key length exceeding four bytes is appended to the end of the Bucket, and the element value is likely to be a zval structure. In addition, each array will be allocated an array of Bucket pointers pointed to by arBuckets, although it cannot be said that every time an element is added, A pointer is required, but the situation could be worse. This calculates that one array element will occupy 54 bytes, which is almost the same as the above estimate.

An empty array will occupy at least 14(zval) 39(HashTable) 33(arBuckets) = 86 bytes. As a variable, it should have a position in the symbol table and is also an array element, so an empty array Array variables require 118 bytes to describe and store. From a space perspective, small arrays are more expensive on average. Of course, a script will not be filled with a large number of small arrays, and programming convenience can be obtained at a smaller space cost. But if you use an array as a container, it's a different story. In practical applications, you often encounter multi-dimensional arrays with many elements. For example, a one-dimensional array of 10k elements consumes about 540k of memory, while a 10k The array actually consumes 23M, and small arrays are really not worth it.

The above is the detailed content of PHP array memory usage analysis. For more information, please follow other related articles on the PHP Chinese website!

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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to use PHP arrays to generate and display charts and statistical graphs How to use PHP arrays to generate and display charts and statistical graphs Jul 15, 2023 pm 12:24 PM

How to use PHP arrays to generate and display charts and statistical graphs. PHP is a widely used server-side scripting language with powerful data processing and graphic generation capabilities. In web development, we often need to display charts and statistical graphs of data. Through PHP arrays, we can easily implement these functions. This article will introduce how to use PHP arrays to generate and display charts and statistical graphs, and provide relevant code examples. Introducing the necessary library files and style sheets Before starting, we need to introduce some necessary library files into the PHP file

How to use PHP arrays to generate dynamic slideshows and image displays How to use PHP arrays to generate dynamic slideshows and image displays Jul 15, 2023 pm 01:17 PM

How to use PHP arrays to generate dynamic slideshows and picture displays. Slideshows and picture displays are common functions in web design and are often used in scenarios such as carousels and gallery displays. As a popular server-side scripting language, PHP has the ability to process data and generate dynamic HTML pages, and is very suitable for generating dynamic slideshows and picture displays. This article will introduce how to use PHP arrays to generate dynamic slideshows and picture displays, and give corresponding code examples. Prepare image data First, we need to prepare a set of image path data

What are the functions for averaging arrays in php? What are the functions for averaging arrays in php? Jul 17, 2023 pm 04:03 PM

PHP array averaging functions include: 1. array_sum(), which is used to calculate the sum of all values ​​in the array. In order to calculate the average, you can add all the values ​​in the array and then divide by the number of array elements; 2 , array_reduce(), used to iterate the array and calculate each value with an initial value; 3. array_mean(), used to return the average of the array, first calculate the sum of the array, and calculate the number of array elements, then The sum is divided by the number of array elements to get the average.

How to use PHP arrays to implement user login and permission management functions How to use PHP arrays to implement user login and permission management functions Jul 15, 2023 pm 08:55 PM

How to use PHP arrays to implement user login and permission management functions When developing a website, user login and permission management are one of the very important functions. User login allows us to authenticate users and protect the security of the website. Permission management can control users' operating permissions on the website to ensure that users can only access the functions for which they are authorized. In this article, we will introduce how to use PHP arrays to implement user login and permission management functions. We'll use a simple example to demonstrate this process. First we need to create

What are php array key-value pairs? What are php array key-value pairs? Aug 03, 2023 pm 02:20 PM

PHP array key-value pair is a data structure consisting of a key and a corresponding value. The key is the identifier of the array element, and the value is the data associated with the key. It allows us to store and access data using keys as identifiers. By using key-value pairs, we can more easily operate and manage elements in the array, making program development more flexible and efficient.

An exploration of performance optimization techniques for PHP arrays An exploration of performance optimization techniques for PHP arrays Mar 13, 2024 pm 03:03 PM

PHP array is a very common data structure that is often used during the development process. However, as the amount of data increases, array performance can become an issue. This article will explore some performance optimization techniques for PHP arrays and provide specific code examples. 1. Use appropriate data structures In PHP, in addition to ordinary arrays, there are some other data structures, such as SplFixedArray, SplDoublyLinkedList, etc., which may perform better than ordinary arrays in certain situations.

How to convert a two-dimensional php array into a one-dimensional array How to convert a two-dimensional php array into a one-dimensional array Aug 03, 2023 am 11:14 AM

How to convert a php array from two dimensions to a one-dimensional array: 1. Use loop traversal to traverse the two-dimensional array and add each element to the one-dimensional array; 2. Use the "array_merge" function to merge multiple arrays into An array. Pass the two-dimensional array as a parameter to the "array_merge" function to convert it into a one-dimensional array; 3. Using the "array_reduce" function, you can process all the values ​​in the array through a callback function and finally return a result.

How to determine how many arrays there are in php How to determine how many arrays there are in php Aug 04, 2023 pm 05:40 PM

There are several ways to determine an array in PHP: 1. Use the count() function, which is suitable for all types of arrays. However, it should be noted that if the parameter passed in is not an array, the count() function will return 0; 2. Use the sizeof() function, which is more used to maintain compatibility with other programming languages; 3. Custom functions, By using a loop to traverse the array, each time it is traversed, the counter is incremented by 1, and finally the length of the array is obtained. Custom functions can be modified and expanded according to actual needs, making them more flexible.

See all articles