[Project_owners] how to implement bounded stack in javascript?

Axel Hecht axel at pike.org
Sat Apr 15 19:43:02 EDT 2006


Eric H. Jung wrote:
> Hi,
> 
> I'm trying to implement a custom <tree/> view which displays the most recent 500 log messages
> (row0 = most recent, row499 = oldest). What's the most efficient way to implement a bounded stack
> (LIFO buffer) in javascript?
> 
> I was thinking this:
> 
> var boundedStack = new Array(500);
> function push(o) {
>   if (boundedStack.unshift(o) > 500)
>     boundedStack.pop();
> }
> 
> Is there anything more efficient? I'm looking for the most performant implementation.
> 
> Thank you for any advice,
> Eric H. Jung
> FoxyProxy--Take Back Your Privacy!  (Coming This Weekend)
> 

Now that is sure as hell dog as slow.

You don't want to shift your entries each time.

The next question to ask is, are you frequently going to hit 500 
messages? Or are you most of the time fine with 25? That determines how 
much of the array you want to allocate to boot with.

Then I'd recommend having a 'currentIndex' member, and cycle that 
around. That way, you never move the 499 items inside the array that you 
didn't intend to change.

Axel


More information about the Project_owners mailing list