in reply to Efficiency Question

#2. In the check() function, if a hit is found, I would like the item move to the top of the list (representing it should stay in the cache longer). What I need to do is remove the current item ($_ as it stands now) and tack it on to the end of the list via a push. How would you recommend doing it? I dont care about cleverness, or obsfucation, but raw number of instructions. I had though of doing an undef $_; inside the loop, but that doesn't seem to actually remove the item from the array, just undef it out (the list continues to have the same # of elements). I suspect I need to splice it, but without having the index of the element of the array, I couldn't figure out how to do it... efficiently.
You hit the nail on the head. Setting aside efficiency (I have a whole rant prepared for that) trying to splice up an array while iterating over it with for(LIST) is tough business. The easiest thing to do is to attack it with a for(init; test; increment) loop:
sub remove5s { my($aref)=@_; for(my $i=0; $i<@$aref; $i++) { $_=$$aref[$i]; unless ($_ % 5) { splice(@$aref, $i, 1); $i--; } } }
This sub removes elements that are evenly divisible by 5. Rather than splice them out, it could just as easily have pushed them onto the end of the list (but you didn't say which list) or swapped it with the element at the end (watch for terminal conditions!).

Replies are listed 'Best First'.
Re: Re: Efficiency Question
by riffraff (Pilgrim) on Feb 23, 2001 at 21:42 UTC
    Without much research here, wouldn't an AVL tree do what you would like to do? It is optimized (I believe; I hope I'm remembering the correct algorithm) for this type of thing; most often used items are moved to the top, and it is self-balancing too (I believe).