Our database is often very large, and the result set of a query is also very large, which wastes memory. In order to reduce memory usage, we can use yii2's batch and each method.
In order to let everyone see more clearly, we simulate a scenario, and then use the debug of yii2 to view the memory usage under the all and batch/each methods.
Start preparation
We first create a table, it is very simple.
You see, it has the primary key id, member name username, and province. Now it is empty.
Then, we executed a loop
set_time_limit(0); for($i=1;$i<=10000;$i++){ Yii::$app->db->createCommand()->insert("user",[ 'username'=>'abei'.$i, 'province'=>'北京市' ])->execute(); }
After execution, you know that there are 10,000 records in our database, and now we start to compare.
Comparison
For convenience, we write the loop body directly in the view, such as the following code, you can definitely understand it.
$query = new \yii\db\Query(); $query->from('user'); foreach($query->all() as $user){ echo $user['username']; echo "<br/>"; }
The result?
Occupied memory 15.306MB
OK, now let’s see if the tricks of batch and each save memory.
$query = new \yii\db\Query(); $query->from('user'); foreach($query->batch() as $users){ foreach($users as $user){ echo $user['username']; echo "<br/>"; } }
The result?
# Sure enough, half of the memory was saved. Now it only takes up 8.077MB
The same
$query = new \yii\db\Query(); $query->from('user'); foreach($query->each() as $user){ echo $user['username']; echo "<br/>"; }
each performance is also quite good
Result
When we need to read all or a large batch of data at once, we can consider using batch and each. This little bit of code optimization can help you save half of the memory.
PHP Chinese website has a large number of free Yii introductory tutorials, everyone is welcome to learn!
The above is the detailed content of What is the difference between yii2 batch and each. For more information, please follow other related articles on the PHP Chinese website!