1.在测试数据库连接效率时,会遇到这种情况
<?php
header('content-type:text/html;charset=utf-8');
//1.通过PDO连接数据库
$pStartTime=microtime(true);
for($i=1;$i<=100;$i++){
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
}
$pEndTime=microtime(true);
$res1=$pEndTime-$pStartTime;
//2.通过MySQL连接数据库
$mStartTime=microtime(true);
for($i=1;$i<=100;$i++){
$con=mysqli_connect('localhost','root','root');
mysqli_select_db($con,'test');
}
$mEndTime=microtime(true);
$res2=$mEndTime-$mStartTime;
echo $res1.'<br/>'.$res2;
echo '<hr/>';
if($res1>$res2){
echo 'PDO连接数据库MySQL的'.round($res1/$res2).'倍';
}else{
echo 'MySQL连接数据库PDO的'.round($res2/$res1).'倍';
}
按照上面代码测试,会出现连接超时(超过30秒),就算是就重复连接3次两次,时间也会比较长。
这时候把localhost改为127.0.0.1连接速度就会变得正常。
测试结果:
0.94578814506531
1.0991640090942
MySQL连接数据库PDO的1倍
2.另外还有一种方式也可以提升连接速度就是用长连接
<?php
header('content-type:text/html;charset=utf-8');
//1.通过PDO连接数据库
$pStartTime=microtime(true);
for($i=1;$i<=100;$i++){
$pdo=new PDO('mysql:host=127.0.0.1;dbname=test','root','root', array(PDO::ATTR_PERSISTENT => true));
}
$pEndTime=microtime(true);
$res1=$pEndTime-$pStartTime;
//2.通过MySQL连接数据库
$mStartTime=microtime(true);
for($i=1;$i<=100;$i++){
$con=mysqli_connect('127.0.0.1','root','root');
mysqli_select_db($con,'test');
}
$mEndTime=microtime(true);
$res2=$mEndTime-$mStartTime;
echo $res1.'<br/>'.$res2;
echo '<hr/>';
if($res1>$res2){
echo 'PDO连接数据库MySQL的'.round($res1/$res2).'倍';
}else{
echo 'MySQL连接数据库PDO的'.round($res2/$res1).'倍';
}
注意连接pdo时的变化