php优化数组,php – 优化数组合并操作

鉴于,我将不胜感激任何帮助.

我有7个单独的阵列与约.每个数组中有90,000个数字(我们称之为arrays1-arrays7).每个数组本身都没有重复的数字.但是,阵列之间可能存在重复.例如,array2没有重复项,但可以使用与arrays3和arrays4相同的数字.

问题:

一旦所有7个阵列合并,我试图识别所有重复3次的数字.

我必须进行1000次计算,需要15分钟,但这不行,因为我必须运行40次 – 代码:

如果您知道另一种最适合此类计算的语言,请告诉我.任何扩展建议,如redis或gearman都有帮助.

for($kj=1; $kj<=1000; $kj++)

{

$result=array_merge($files_array1,$files_array2,$files_array3,$files_array4,$files_array5,$files_array6,$files_array7);

$result=array_count_values($result);

$fp_lines = fopen("equalTo3.txt", "w");

foreach($result as $key => $val)

{

if($result[$key]==3)

{

fwrite($fp_lines, $key."\r\n");

}

}

fclose($fp_lines);

}

我也用字符串尝试了下面的代码,但是array_map调用和array_count值调用需要17分钟:

for($kj=1; $kj<=1000; $kj++)

{

$result='';

for ($ii = 0; $ii< 7; $ii++) {

$result .= $files_array[$hello_won[$ii]].'\r\n';

}

$result2=explode("\n",$result);//5mins

$result2=array_map("trim",$result2);//11mins

$result2=array_count_values($result2);//4-6mins

$fp_lines = fopen("equalTo3.txt", "w");

foreach($result2 as $key => $val)

{

if($result2[$key]==3)

{

fwrite($fp_lines, $key."\r\n");

}

}

fclose($fp_lines);

unset($result2);

// /

@ziumin @ailvenge @scunliffe @ this.lau_ @monocell感谢所有发帖的人!我正在处理你的所有建议,并在我完成所有答案后明天接受答案.非常感谢!

解决方法:

array_merge()在数组中有更多元素时显着变慢,因为(从php.net开始):

If the input arrays have the same string keys, then the later value

for that key will overwrite the previous one. If, however, the arrays

contain numeric keys, the later value will not overwrite the original

value, but will be appended.

Values in the input array with numeric keys will be renumbered with

incrementing keys starting from zero in the result array.

所以这个函数实际上是在做一些条件语句.您可以使用正常添加替换数组合并,包括循环(foreach或任何其他)和[]运算符.你可以写一个模仿array_merge的函数,比如(使用引用不复制数组..):

function imitateMerge(&$array1, &$array2) {

foreach($array2 as $i) {

$array1[] = $i;

}

}

你会看到速度的提高真的很难.

标签:php,optimization,arrays,performance

来源: https://codeday.me/bug/20190528/1174096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值