?
This document uses PHP Chinese website manual Release
<?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) . '倍'; }