mysqli 比 mysql 速度_PDO 与 MySQLi 二者效率简单比较

# PDO 与 MySQLi 二者效率简单比较

## 连接效率比较

```

$p_start_time = microtime(true);

for ($i = 1; $i <= 100; $i++) {

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'aaaaaa');

}

$p_end_time = microtime(true);

$res = $p_end_time - $p_start_time; // PDO 连接方式耗时

$m_start_time = microtime(true);

for ($i = 1; $i <= 100; $i++) {

mysqli_connect('localhost', 'root', 'aaaaaa', 'test');

}

$m_end_time = microtime(true);

$res2 = $m_end_time - $p_start_time; // MySQL 连接方式耗时

var_dump($res, '
', $res2);

if ($res > $res2) {

echo 'PDO 连接数据库是 MySQL 的' . round($res2 / $res) . '倍';

} else {

echo 'MySQL 连接数据库是 PDO 的' . round($res2 / $res) . '倍';

}

```

## 写入速度比较

```

// PDO 与 MySQLi 两种连接方式写入效率简单比较

$p_start_time = microtime(true);

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'aaaaaa');

// 写入数据表

$sql = <<

CREATE TABLE IF NOT EXISTS test(

id int unsigned not null

)ENGINE=InnoDB CHARSET utf8 comment '写入测试表';

EOF;

$pdo->exec($sql);

// 使用 PDO 预处理语句写入 500 条数据到数据库

$sql = 'INSERT INTO test VALUES(:id)';

$statement = $pdo->prepare($sql);

for ($i = 1; $i <= 500; $i++) {

$id = 1;

$statement->bindParam(':id', $id, PDO::PARAM_INT);

$statement->execute();

}

unset($pdo); // 销毁 PDO 对象

$p_end_time = microtime(true);

$res = $p_end_time - $p_start_time; // PDO 连接方式耗时

$m_start_time = microtime(true);

// 使用 MySQLi 连接方式写入 500 条数据到数据库

$link = mysqli_connect('localhost', 'root', 'aaaaaa', 'test');

for ($i = 1; $i <= 500; $i++) {

$sql = 'INSERT INTO test VALUES (2)';

mysqli_query($link, $sql);

}

mysqli_close($link); // 关闭连接

$m_end_time = microtime(true);

$res2 = $m_end_time - $p_start_time; // MySQL 连接方式耗时

var_dump($res, '
', $res2);

if ($res > $res2) {

echo 'PDO 连接数据库写入速度是 MySQL 的' . round($res2 / $res) . '倍';

} else {

echo 'MySQL 连接数据库写入速度是 PDO 的' . round($res2 / $res) . '倍';

}

```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值