Ruby: Circular Buffer class

Post any examples or modules that you want to share here
Post Reply
User avatar
trogluddite
Posts: 1730
Joined: Fri Oct 22, 2010 12:46 am
Location: Yorkshire, UK

Ruby: Circular Buffer class

Post by trogluddite »

Hi All,
Here's a little class that knocked up for making circular buffers - i.e. An Array where you push items to the end, and they are removed from the top when the buffer gets too big (FIFO).
Circular Buffer.fsm
(132.5 KiB) Downloaded 1492 times

A glance at the Ruby API docs will turn up what looks like a very simple way to do this...

Code: Select all

@myArray = Array(new)
@max_size = 100
# Put an item on the end of the array
@myArray << item
# Shorten the Array if it got too big
@myArray.shift if @myArray.size > @max_size

But there's a problem with this...
At the start, each time you push something, the array grows. Once the max size is reached, it both grows and shrinks each time an item is added. Each time the array changes size, Ruby has to go crawling to the operating system to sort out the memory allocation - and this has a pretty heavy CPU cost.
The CircularBuffer class does away with that; keeping a fixed amount of memory in use at all times - some benchmark tests showed a two to ten times speed increase when adding items (it gets more efficient the bigger the buffer size, especially once it starts 'circulating').

However, reading the data is slower, as it has to be 'straightened out' from its 'circular' format. So this class is ideal for applications like data logging or MIDI analysers where many quick-fire input events only need reading every once in a while.

More documentation and examples in the schematic.

Happy new year!
All schematics/modules I post are free for all to use - but a credit is always polite!
Don't stagnate, mutate to create!
Post Reply