Home > Article > Backend Development > PHP code optimization array_push
There are usually several types of data inserted into arrays in PHP:
$arr = array(‘apple’, ’banana’);
$arr = array(); $arr[] = ‘apple’; $arr[] = ‘banana’;
$arr = array(‘apple’); array_push($arr, ‘banana’, ‘orange’);
In most cases, we first obtain data from the database and then convert it into an array form. For the first case, direct assignment when defining the array is often only suitable for situations where the amount of data is small and known, so there is no code optimization. We mainly talk about the second and third cases.
We used php 7.2
for testing and did not make any configuration optimization. Test method: Define an array and insert 100,000 records using the second and third methods respectively. The code is roughly as follows:
#convert function is used to check the memory usage. The running results are as follows:
0.0045, while the method of using
array_push takes about
0.006, and the memory consumed is the same. , because they are all 100,000 records.
array_push, because the function call takes some time in each loop, but just looking at the above test, I don’t feel that the second method is faster than calling
array_push
Let’s take a look at the difference between the two.
array_push() is a function call and the other is not. That is to say, the two are the same in terms of code size. From the array From a structural point of view, we did not use indexes in the test. The default is to start from 0. If you want to use the
key => value form to insert data,
array_push() is not very convenient. It’s easy to handle. It’s very convenient to use method 2 at this time:
$array1[$key] => $x
It was said before that
array_push() is not good, but sometimes
array_push
$arr = array(‘a’, ’b’); array_push($arr, ‘c’, ‘d’); // $arr = array(‘a’, ’b’, ‘c’, ‘d’);As can be seen from the above comparison, there are many methods of array interpolation in PHP. Although each method is similar, it is important to understand when each method It is still necessary to use it.
Related courses: PHP video tutorial
###The above is the detailed content of PHP code optimization array_push. For more information, please follow other related articles on the PHP Chinese website!