字符串连接导致超时
下面是我最近添加到 PHP 中的一段代码,它接受一个整数数组 ($naEUS) 并对其进行迭代,在数字之间添加逗号,但在开始和结束时有一些例外。最终结果应该是一个如下所示的字符串: ( ### , ### , ### , ### )
$num = count( $naEUS[$f] );
$resultsFields_values = "(";
for( $b = 0; $b < $num; $b++ )
{
if( $b = 0 )
{
$resultsFields_values = substr_replace( $resultsFields_values, " {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
}
$resultsFields_values = substr_replace( $resultsFields_values, ", {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
}
$resultsFields_values = substr_replace( $resultsFields_values, ")" , ( strlen($resultsFields_values) ), 0);
我意识到有很多线程解决字符串连接问题,但它们只解决部分 我的问题。我知道这是一种极其低效的方法。他们展示了一种更好的方法,但很容易找到。
我真正想知道为什么我的 PHP 运行时间为 5 秒,却超时了 30 秒。
当然,也欢迎更好的解决方案。
Below I have a segment of my code that I recently added to my PHP, which takes an array of integers ($naEUS) and iterates though it, appending the numbers with commas in between with a few exceptions for the start and finish. The end result should be a string that looks like this: ( ### , ### , ### , ### )
$num = count( $naEUS[$f] );
$resultsFields_values = "(";
for( $b = 0; $b < $num; $b++ )
{
if( $b = 0 )
{
$resultsFields_values = substr_replace( $resultsFields_values, " {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
}
$resultsFields_values = substr_replace( $resultsFields_values, ", {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
}
$resultsFields_values = substr_replace( $resultsFields_values, ")" , ( strlen($resultsFields_values) ), 0);
I realize there are plenty of threads addressing string concatenation, but they only address part of my problem. I know this is a horribly inefficient way of doing this. and they show a better way of doing it, but that's easy to find.
What I really want to know is why it took my 5 second run time PHP to it's 30 second timeout.
Of course, better solutions are also welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
$b = 0
,您可以在每次迭代时将循环重置为零。=
用于赋值,==
用于相等测试。With
$b = 0
, you're resetting the loop back to zero on every iteration.=
is for assignment,==
is for equality testing.嗯,这取决于数组的大小,但您在这里所做的是使用相当低效的函数在每次迭代中重新分配该字符串。只要您的数组很小,这可能就可以正常工作,但是当它包含数千个项目时,执行需要很长时间也就不足为奇了。
更好的解决方案是使用 implode 函数,如下所示:
Well, it depends on the size of the array, but what you're doing here is reallocating that string in every iteration using a rather inefficient function. This will probably work fine as long as your array is small, but when it contains a couple of thousands of items, it's not wonder that execution takes long.
A better solution would be to use the implode function, like this:
使用比较运算符 == 而不是 $b = 0。
Use comparison operator == instead of $b = 0.