在 PDO 中,如果将 int 引用为字符串,性能会有所不同吗?
In PDO is there a difference in performance if a int is quoted as a string?
如果在准备好的 PDO 查询中将整数绑定为字符串,性能会有差异吗?在 Mysql 中,如果值绑定为 int 或字符串,查询将起作用,但性能是否有任何差异,或者这样做时是否有任何陷阱?
$pdo = new PDO(
"mysql:host={$host};port={$port};dbname={$dbname};charset=utf8",
$username,
$password
);
$statement = $pdo->prepare("SELECT * FROM `table` WHERE `id` = :param");
// Is there any performance difference between the two rows below
$statement->bindValue(":param", 5);
$statement->bindValue(":param", 5, PDO::PARAM_INT);
$statement->execute();
绑定参数和指定其类型,或者只是将其作为字符串引用之间有什么区别吗?
如果你想准确地使用它,你指定类型的方法比你不指定类型的方法稍微快一些,默认类型是 PDO::PARAM_STR
.
如果你 运行 100 万次 avarage 如下:
- 指定的 int 类型:0.53 秒 (
$stmt->bindValue(":param", 5, PDO::PARAM_INT);
)
- 未指定类型:0.66 秒 (
$stmt->bindValue(":param", 5);
)
- str 类型指定:0.70 秒 (
$stmt->bindValue(":param", 5, PDO::PARAM_STR);
)
使用 PHP 版本 5.6.3 测试; 32 位 Windows;
根据我的经验,没有这种性能差异。
MySQL 自动将字符串转换为数字(取决于列类型)。
准确地说,PDO::PARAM_STR 比 PDO::PARAM_INT 慢。
PDO::PARAM_STR 是默认的。
这是因为服务器要检查你的数据。
如果在准备好的 PDO 查询中将整数绑定为字符串,性能会有差异吗?在 Mysql 中,如果值绑定为 int 或字符串,查询将起作用,但性能是否有任何差异,或者这样做时是否有任何陷阱?
$pdo = new PDO(
"mysql:host={$host};port={$port};dbname={$dbname};charset=utf8",
$username,
$password
);
$statement = $pdo->prepare("SELECT * FROM `table` WHERE `id` = :param");
// Is there any performance difference between the two rows below
$statement->bindValue(":param", 5);
$statement->bindValue(":param", 5, PDO::PARAM_INT);
$statement->execute();
绑定参数和指定其类型,或者只是将其作为字符串引用之间有什么区别吗?
如果你想准确地使用它,你指定类型的方法比你不指定类型的方法稍微快一些,默认类型是 PDO::PARAM_STR
.
如果你 运行 100 万次 avarage 如下:
- 指定的 int 类型:0.53 秒 (
$stmt->bindValue(":param", 5, PDO::PARAM_INT);
) - 未指定类型:0.66 秒 (
$stmt->bindValue(":param", 5);
) - str 类型指定:0.70 秒 (
$stmt->bindValue(":param", 5, PDO::PARAM_STR);
)
使用 PHP 版本 5.6.3 测试; 32 位 Windows;
根据我的经验,没有这种性能差异。 MySQL 自动将字符串转换为数字(取决于列类型)。
准确地说,PDO::PARAM_STR 比 PDO::PARAM_INT 慢。 PDO::PARAM_STR 是默认的。
这是因为服务器要检查你的数据。