PHP编程实例:PDO 与 MySQLi 二者效率简单比较

2020-07-2817:50:36后端程序开发Comments1,567 views字数 1745阅读模式

连接效率比较

<?php

$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, '<br />', $res2);
if ($res > $res2) {
    echo 'PDO 连接数据库是 MySQL 的' . round($res2 / $res) . '倍';
} else {
    echo 'MySQL 连接数据库是 PDO 的' . round($res2 / $res) . '倍';
}

写入速度比较

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

$p_start_time = microtime(true);
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'aaaaaa');
// 写入数据表
$sql = <<<EOF
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, '<br />', $res2);
if ($res > $res2) {
    echo 'PDO 连接数据库写入速度是 MySQL 的' . round($res2 / $res) . '倍';
} else {
    echo 'MySQL 连接数据库写入速度是 PDO 的' . round($res2 / $res) . '倍';
}
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19917.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/19917.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定