search
HomeBackend DevelopmentPHP TutorialPHP array merging method: array_merge VS array_push VS element append

PHP array merging method: array_merge VS array_push VS element append

Jul 07, 2021 pm 07:13 PM
array_mergearray_pushphpArray merge

This article will share with you three PHP array merging methods: array_merge, array_push and element append method, and compare their performance and memory consumption.

PHP array merging method: array_merge VS array_push VS element append

To implement array merging in PHP, there are two commonly used methods:

  • Use array_merge directly. Although this method does the code It is simple, but it greatly increases the memory overhead and slows down the performance of PHP.
  • Traverse the array and append the values ​​in the array to the result array one by one. Compared with using array_merge directly, although this method increases the amount of code, it reduces PHP's memory overhead and improves performance. .

##⒈ Code implementation

/**
    用 PHP 实现将一个二维数组合并为一个一维数组
*/
// 数组的长度
$len = $argv[1];

$start = 0;
$arr = [];
// 数组初始化
while ($start < $len) {
    $arr[$start] = range(1, $len);
    $start ++;
}
// 采用 array_merge 的方式合并数组
function merge1 (array $input)
{
    $results = [];

    foreach ($input as $item) {
        $results = array_merge($results, $item);
    }

    return $results;
}
// 采用 array_push 的方式合并数组
function merge2 (array $input) 
{
    $results = [];

    foreach ($input as $item) {
        foreach ($item as $v) {
            array_push($results, $v);
        }
    }

    return $results;
}
// 采用元素追加的方式合并数组
function merge3(array $input)
{
    $results = [];

    foreach ($input as $item) {
        foreach ($item as $v) {
            $results [] = $v;
        }
    }

    return $results;
}

echo microtime(), PHP_EOL;
$res = merge3($arr);
echo microtime(), PHP_EOL;

echo memory_get_usage(), PHP_EOL;
echo memory_get_peak_usage(), PHP_EOL;

⒉ Comparison of running results

Array lengtharray_mergearray_pushElement appendMemory consumption (B)Running time(㎲)Memory consumption(B)Running time(㎲)Memory consumption(B)Running time(㎲)##5505005,000
432,440 20 433,200 25 433,200 19
764,704 322 629,736 141 629,736 102
27,434,944 897,422 19,042,416 11,294 19,042,416 8,182
3,479,599,136 904,476,129 2,405,853,392 1,266,203 2,405,853,392 1,022,328

⒊ Cause Analysis

    When using
  • array_merge

    , each time it is called, new memory needs to be allocated for the result array of array_merge Space (PHP uses a copy-on-write mechanism, and array_merge does not write parameters, so there is no need to reallocate memory for input parameters each time it is called). As the length of the array increases, the number of calls to array_merge will also increase, and the number of reallocations of memory will also increase. At the same time, the length of the result array will continue to increase, and the memory space that needs to be allocated each time will also increase. Increase, which requires consuming a lot of memory. At the same time, frequent allocation/destruction of memory leads to PHP performance degradation.

  • Using
  • array_push

    , you only need to allocate memory to the result array once, and then elements will be appended to the result array. The underlying implementation of PHP array is hashtable, and hashtable will be allocated 8 lengths of bucket during initialization, each bucket Stores an array element. When the existing bucket is used up, if you continue to append elements to the array, PHP will double the number of existing bucket, so use array_push When appending elements to the result array, not every operation requires allocating a new bucket, which reduces the number of memory allocations, speeds up the program running time, and improves PHP performance.

  • The principle of using elements to append is similar to
  • array_push

    . The only difference is that there will be a function call when using array_push, and the element appending The method does not require function calls, so the program will run more lightweight.

  • Recommended learning: "
PHP Video Tutorial

"

The above is the detailed content of PHP array merging method: array_merge VS array_push VS element append. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor