PHP substr()在不使用字符串的第一部分时速度非常慢
我有一个文本文件,大约有5000行,每行大约200个字符长。每行实际上包含6个不同的数据段,我一直在使用PHP substr()在不使用字符串的第一部分时速度非常慢,php,string,substring,Php,String,Substring,我有一个文本文件,大约有5000行,每行大约200个字符长。每行实际上包含6个不同的数据段,我一直在使用substr()来分解这些数据段。例如,在每一行中,字符0-10包含客户机,字符10-20包含问题,等等。这一切都很好,运行速度比我需要的还要快 当我的老板告诉我客户号有4个前导零,需要去掉它们时,我的问题就出现了。所以我想,没问题-我只是将我的第一个substr()函数从substr(0,10)(从0开始,取10个字符)更改为substr(4,6)(从第4个字符开始,取6个字符),这将跳过4
substr()
来分解这些数据段。例如,在每一行中,字符0-10包含客户机,字符10-20包含问题,等等。这一切都很好,运行速度比我需要的还要快
当我的老板告诉我客户号有4个前导零,需要去掉它们时,我的问题就出现了。所以我想,没问题-我只是将我的第一个substr()
函数从substr(0,10)
(从0开始,取10个字符)更改为substr(4,6)
(从第4个字符开始,取6个字符),这将跳过4个前导零,我可以继续了
但是,当我将substr(0,10)
更改为substr(4,6)
时,该过程会停止,并需要永远才能完成。为什么会这样
以下是我的代码片段:
// open the file
$file_matters = fopen($varStoredIn_matters,"r") or exit("Unable to open file!");
// run until the end of the file
while(!feof($file_matters))
{
// place current line in temp variable
$tempLine_matters = fgets($file_matters);
// increment the matters line count
$linecount_matters++;
// break up each column
$clientID = trim(substr($tempLine_matters, 0, 10)); // THIS ONE WORKS FINE
//$clientID = trim(substr($tempLine_matters, 4, 6)); // THIS ONE MAKES THE PROCESS GRIND TO A HALT!!
$matterID = trim(substr($tempLine_matters, 10, 10));
//$matterID = trim(substr($tempLine_matters, 15, 5));
$matterName = trim(substr($tempLine_matters, 20, 80));
$subMatterName = trim(substr($tempLine_matters, 100, 80));
$dateOpen = trim(substr($tempLine_matters, 180, 10));
$orgAttorney = trim(substr($tempLine_matters, 190, 3));
$bilAttorney = trim(substr($tempLine_matters, 193, 3));
$resAttorney = trim(substr($tempLine_matters, 196, 3));
//$tolCode = trim(substr($tempLine_matters, 200, 3));
$tolCode = trim(substr($tempLine_matters, 200, 3));
$dateClosed = trim(substr($tempLine_matters, 203, 10));
// just does an insert into the DB using the variables above
}
这不是一个非常优化的过程。你也许应该多想想。 但如果它现在起作用,那是最重要的。。。 也许如果你通过两个过程获得价值,它会更快。例如:
$clientID_bis = trim(substr($tempLine_matters, 0, 10));
$clientID = trim(substr($clientID_bis, 4, 6));
我不明白为什么这样会慢得多,但你可以看看哪一个可以在一次点击中提取出你的固定宽度记录:
$fields = unpack('A10client/A10matter/A60name ...etc... ',$tempLine_matters);
我使用与您的示例类似的记录模式进行了快速基准测试,发现解包的速度是每次迭代中使用10个substr调用的两倍多
我建议您使用xdebug评测代码,看看不同之处。您确定是这样吗?即,它是否适用于较小的数据文件?什么是错误?时间限制?我不能理解。根据实现情况,它不应该产生真正的区别?@AlmaDoMundo我几乎可以肯定的是——更小的数据文件(即200行)处理没有问题。我在大约2分钟时超时,因为这是PHP配置中服务器上设置的最大执行时间。如果我将
substr(4,6)
改回substr(0,10)
它大约在3秒钟内运行5000行。@bwoebi我知道!这就是为什么让我如此沮丧的原因@FastTrack我无法复制$s=str_repeat(“1”,11.41551303863525s
和$s=str_repeat(“1”,11.42793393135071s
我对substr进行了基准测试,试图在没有运气的情况下重复您的发现。您的缓慢是否可以归因于其他一些操作,因为$clientID不像预期的那样需要更长的时间?非常有趣-我从未使用过unpack()
但我会在几分钟后有机会在这里尝试一下。顺便说一句,你用什么来对你的PHP脚本进行基准测试?我在这里看到了很多方法…你知道吗,我试过这个想法,认为它会有所帮助-但我遇到了与我刚刚做substr(4,6)
这是非常奇怪的行为:)如果您对所有其他行进行注释,只保留clientId的substr,则会重现问题?您不能使用$tempLine_事件的分解,以便对较小的字符串使用substr?