0

I've been using a function I made when I first started programming (Or shortly thereafter at least) to do the simple but extremely useful task of organizing an array based on parents and children. An example of where this would be useful would be for, say, if you had a list of items that can have an infinite depth of children in a database, and you need to present the list in order in an html select element with a visual representation (--) of depth for each child.

Now, I have the function(s) that do this, and they work under all the situations that I've put them in, however they clone the array countless times... So far this hasn't been an issue, but I'm starting to use this function in places that could have tens of thousands of entries it needs to organize. So I'm hoping someone here could help me optimize it.

The code: http://pastebin.com/knk0Fyd0

Jon
  • 305
  • 3
  • 20
  • 45

1 Answers1

1

Take the count() function out of the loop. It's a bottleneck. Instead of:

for ($i=0;$i<count($array);$i++)

Use this:

$count=count($array);
for ($i=0;$i<$count;$i++)

Your InsertAfter() function could have been easily accomplished with PHP's array_splice() and/or array_slice().

bcosca
  • 17,371
  • 5
  • 40
  • 51
  • Thanks that's a pretty significant speed increase, but I'm curious... Am I loading the array into memory again and again or is PHP smart enough to handle it properly? – Jon Nov 25 '10 at 15:48
  • 1
    You're manipulating the arrays inside a function. When your function is done, PHP's garbage collector takes over and frees up space. If you can break up that large function into smaller ones, your memory consumption will go down. – bcosca Nov 25 '10 at 15:54
  • Alright thanks a bunch... Also I just ran this on a randomly generated 200 entry long array, and it takes 2ms to run. Are there any other ways to speed it up? Or, is there some way to cache an array? I have a cache function built, but I'm not sure how I can get a unique ID for each array to make sure a cache for it hasn't already been generated. md5(var_dump())? – Jon Nov 25 '10 at 16:48
  • @Jon sounds like you're using an Adjacency List approach for storing your data (e.g. id & parentId for each record). If read performance is the primary concern, and you're using a RDBMS for persistence, consider some of the other options listed here: http://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database – orangepips Nov 26 '10 at 16:10