【发布时间】:2021-10-22 09:34:38
【问题描述】:
我的 while 循环中有以下代码,而且速度非常慢,有什么改进的建议吗?
open IN, "<$FileDir/$file" || Err( "Failed to open $file at location: $FileDir" );
my $linenum = 0;
while ( $line = <IN> ) {
if ( $linenum == 0 ) {
Log(" This is header line : $line");
$linenum++;
} else {
$linenum++;
my $csv = Text::CSV_XS->new();
my $status = $csv->parse($line);
my @val = $csv->fields();
$index = 0;
Log("number of parameters for this file is: $sth->{NUM_OF_PARAMS}");
for ( $index = 0; $index <= $#val; $index++ ) {
if ( $index < $sth->{NUM_OF_PARAMS} ) {
$sth->bind_param( $index + 1, $val[$index] );
}
}
if ( $sth->execute() ) {
$ifa_dbh->commit();
} else {
Log("line $linenum insert failed");
$ifa_dbh->rollback();
exit(1);
}
}
}
【问题讨论】:
-
数据库操作将成为您的瓶颈。如果这些确实是“插入”,那么您可以批量插入,而不是为每个插入使用数据库事务。
-
不要为循环的每次迭代创建一个新的
Text::CSV_XS对象。而是创建它并使用它的getline方法循环文件。 -
请为您正在使用的 DBMS 添加标签。此外,您可以使用this 分析您的代码。它并不完美,但对于您显示的代码来说可能已经足够了。
-
谁能举例说明如何进行批量插入,因为它是瓶颈并且性能仍然很慢。
-
@Jeg CSV 文件字段中的代码
bind_params到NUM_OF_PARAMS。 CSV 文件的行之间的字段数可以更改吗?您是否总是像看起来那样绑定 CSV 文件的第一个NUM_OF_PARAMS字段?
标签: database performance perl while-loop file-read