gpt4 book ai didi

php - 使用 php 的 mysqli 准备好的语句很慢

转载 作者:行者123 更新时间:2023-11-29 00:03:36 25 4
gpt4 key购买 nike

我有大约 2000-3000 条记录需要存储在 mysql 数据库中,我使用的是 php。我正在使用准备好的语句来执行此操作,但与使用普通查询相比,速度下降到原来的 1/3!

显示我使用它们的 php 如下。

$connection = ...; // a mysqli object
$tile;
$xPos;
$yPos;
$isPass; //variables used in the prep statement.

$insertPrepS = $connection->prepare("INSERT INTO `foo`.`tiles`(MapId,XPos,YPos,Passable) VALUES(?,?,?,?)");
$insertPrepS->bind_param("iiii",$mapId,$xPos,$yPos,$isPass); //$mapId was set up earlier in the code.

$map = new Map(50,50); //has w and h and an array of Tile objects inside.
$map->generateMap(); //sets up the array of Tile objects inside the map

for($y = 0; $y < $map->h; $y++){
for($x = 0; $x < $map->w; $x++){
$tile = $map->getTile(0,0);
$xPos = $tile->x;
$yPos = $tile->y;
$isPass = $tile->passable?1:0;
$insertPrepS->execute();
}
}

表 'tiles' 有两个索引,一个主键(自动递增,所以在这里省略)和一个外键 'MapId',我在程序的前面声明和定义了它的值。

我在这里使用准备好的语句是否正确?为什么它的运行速度比没有它们慢得多,除此之外我还能做些什么来提高插入记录的速度?

最佳答案

  1. 您对准备好的语句的使用似乎是合法的。
  2. 您可以在一个事务中应用您的插入查询。

简化示例

$connection->begin_transaction();
for($y = 0; $y < $map->h; $y++){
for($x = 0; $x < $map->w; $x++){
$tile = $map->getTile(0,0);
$xPos = $tile->x;
$yPos = $tile->y;
$isPass = $tile->passable?1:0;
$insertPrepS->execute();
}
}
$connection->commit();

不要忘记在出错时回滚。

附言MySQL transaction size - how big is too big?

关于php - 使用 php 的 mysqli 准备好的语句很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28535075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com