PHP in_array()可怕的性能。搜索数组值Fatest方式 [英] PHP in_array() horrible performance. Fatest way to search array for value

查看:137
本文介绍了PHP in_array()可怕的性能。搜索数组值Fatest方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的code,以测试对碰撞在主键上我创造:

  $ machine_ids =阵列();为($ I = 0; $ I< 100000; $ I ++){
    //生成机器ID返回15字符的字母数字字符串
    $中旬=功能:: generate_machine_id();    如果(in_array($中旬,$ machine_ids)){
        死(碰撞!);
    }其他{
        $ machine_ids [] = $中旬;
    }
}死(成功!);

知道为什么这是采取了许多分钟跑?反正要加快步伐?


解决方案

 为($ I = 0; $ I< 100000; $ I ++)
{
  //生成机器ID返回15字符的字母数字字符串
  $中旬=功能:: generate_machine_id();
  如果(使用isset($ machine_ids [$中旬))
  {
    死(碰撞!);
  }
  $ machine_ids [$中旬] =真;
}

I have the following simple code to test against collision on a primary key I am creating:

$machine_ids = array();

for($i = 0; $i < 100000; $i++) {
    //Generate machine id returns a 15 character alphanumeric string
    $mid = Functions::generate_machine_id();

    if(in_array($mid, $machine_ids)) {
        die("Collision!");
    } else {
        $machine_ids[] = $mid;  
    }
}

die("Success!");

Any idea why this is taking many minutes to run? Anyway to speed it up?

解决方案

for($i = 0; $i < 100000; $i++) 
{
  //Generate machine id returns a 15 character alphanumeric string
  $mid = Functions::generate_machine_id();
  if (isset($machine_ids[$mid]))
  {
    die("Collision!");
  }
  $machine_ids[$mid] = true;
}

这篇关于PHP in_array()可怕的性能。搜索数组值Fatest方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆