Reply to Re: How to avoid in_array() function.

Your name:

Reply:


Posted by Michael Winter on 12/04/05 18:55

On 04/12/2005 15:34, Berimor wrote:

[snip]

> $first=range("a","z");
> $second=range("a","z");
> $third=range("a","z");
> $all_arr=array();
>
> foreach ($first as $f){
> foreach ($second as $s){
> foreach ($third as $t){
> $ind=$f.$s.$t;
> if (!in_array($ind,$all_arr)) $all_arr[]=$ind;
> }
> }
> }

[snip]

> It prints the time script worked. Guess the number?
> 250(!!!!) seconds!!!

I'm not that surprised, though it took just less than a minute here. Do
you understand how much work you're expecting PHP to do?

In each iteration of the innermost loop, 'ind' will be assigned a unique
value. The in_array function must then search 'all_arr' and attempt to
find it. As it will never exist, the function will perform an exhaustive
search, eventually returning false.

In the first iteration, 'all_arr' will be empty. In the second, it will
have one element. By the final iteration, 'all_arr' will contain 17,575
elements (the final one yet to be added). To reach, and finally execute,
the final assignment, the in_array function will have performed
154,449,100 string comparisons (the sum of the number of elements on
each iteration) without a single match. The rest of the code will have
its own overheads, too.

> Is there any alternative in PHP to check array?

It would seem that a better algorithm is what you really need. On this
machine, removing the if statement reduced the execution time to about
60ms: approximately 93 times faster.

Why do you think you need to keep checking the values in the array? If
you explain what you're doing, someone may be able to show you an
alternative approach.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация