Prepared Statement(預處理語句)常被宣稱能提升查詢效能並防止 SQL 注入。本文透過實際程式碼測試,對比 mysqli::query() 與 mysqli::prepare() 在不同數據量下的執行時間差異。
<?php
class Timer {
private $startTime = 0;
private $stopTime = 0;
private $timeSpent = 0;
public function start() {
$this->startTime = microtime(true);
}
public function stop() {
$this->stopTime = microtime(true);
}
public function spent() {
if ($this->timeSpent) return $this->timeSpent;
$this->timeSpent = round($this->stopTime - $this->startTime, 8);
return $this->timeSpent . '秒';
}
}
$timer = new Timer();
$timer->start();
$mysqli = new mysqli('localhost', 'root', 'root', 'ganbaobao_ucenter');
// 普通查詢(註解掉,僅作對比參考)
/*
$query = $mysqli->query("SELECT username, email FROM uc_members WHERE uid < 100000");
$result = [];
while ($row = $query->fetch_array()) {
$result[] = ['name' => $row['username'], 'email' => $row['email']];
}
*/
// Prepared Statement 查詢
$stmt = $mysqli->prepare("SELECT username, email FROM uc_members WHERE uid < ?");
$id = 100000;
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($username, $email);
$result = [];
while ($stmt->fetch()) {
$result[] = ['name' => $username, 'email' => $email];
}
$timer->stop();
echo '
預處理查詢 100000 條數據耗時: ' . $timer->spent();
unset($timer);
?>
| 數據量 | 普通查詢 (秒) | Prepared Statement (秒) | 效能提升 |
|---|---|---|---|
| 1,000 條 | 0.011621 | 0.009632 | ~17% |
| 10,000 條 | 0.077669 | 0.046146 | ~41% |
| 100,000 條 | 0.108342 | 0.059899 | ~45% |
execute() 循環