PHP性能优化四(业务逻辑中使用场景)

php脚本性能,很多时候依赖于你的php版本、你的web server环境和你的代码的复杂度。

Hoare曾经说过“过早优化是一切不幸的根源”。当你想要让你的网站更快运转的时候,你才应该去做优化的事情。当你要改变你代码之前,你需要做的事是什么原因引起了系统缓慢?你可以通过以下指导和其他方式优化你的php,可能是数据库原因也可能是网路原因!通过优化你的php代码,你能尝试着找出你的系统瓶颈。  

1.避免循环做SQL操作

经常犯的错误是把一个SQL 操作放置到一个循环中,这就导致频繁的访问数据库,更重要的是,这会直接导致脚本的性能低下。以下的例子,你能够把一个循环操作重置为一个单一的SQL语句。

1 foreach ($userList as $user) {
2   $query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
3   mysql_query($query);
4 }

替换这种循环方案,你能够拼接数据成为一个单一的数据库操作。

1 $userData = array();
2 foreach ($userList as $user) {
3     $userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
4  }
5 $query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);
6 mysql_query($query);

如果这个SQL语句的数据量太大,可以进行分批操作去插入

 1         $count_sql  = "SELECT count(1) as `count` from email_company where status = 0";
 2         $data = $this->db(4)->find($count_sql);
 3         $totle = $data[0]['count'];
 4         $pre_count = 5000;//每次处理5000个条数据
 5         //print_r($data);
 6         for( $i = 0 ;$i < intval($totle/$pre_count)+1 ; $i++ ){
 7 
 8             $sql  = "SELECT distinct(email)  from email_company where status = 0 ";
 9             $sqlRes =  $sql . " limit " . strval($i*$pre_count). ", {$pre_count}";
10             $companyData = $this->db(4)->find($sqlRes);
11             foreach ($companyData as $key => $value) {
12                 $companyEmail[] = "'".$value['email']."'";
13             }
14             $email_string = implode(',', $companyEmail);
15             $sql_211 = "SELECT email , source , addtime from hr_users where fstatus != 0 and email in ($email_string)";
16             $sql_data = $this->db(6)->find($sql_211);
17             foreach ($sql_data as $key => $value) {
18                 $update_sql = "UPDATE email_company set `status` = 1 , `changetime` = '{$value['addtime']}' , `source` = '{$value['source']}' where email = '{$value['email']}'";
19                 $num = $this->db(4)->Exec($update_sql);
20             }
21         }

 精简思路如下:

 1 $totle ; //总数
 2 $pre_count = 5000;//每次处理5000个条数据
 3 for($i = 0 ;$i < intval($totle/$pre_count)+1 ; $i++ ){
 4     $sql  = "SELECT distinct(email)  from email_company where status = 0 ";
 5     $sqlRes =  $sql . " limit " . strval($i*$pre_count). ", {$pre_count}";
 6     $companyData = $this->db(4)->find($sqlRes);
 7     //其他的业务逻辑
 8     *************************
 9 
10 }
原文地址:https://www.cnblogs.com/xs-yqz/p/7452129.html