PDO 与 MySQLi 二者效率简单比较

x33g5p2x  于2021-03-14 发布在 Mysql  
字(1.5k)|赞(0)|评价(0)|浏览(246)

连接效率比较

<?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) . '倍';
}

相关文章

微信公众号

最新文章

更多