šŸ”Circular šŸ’¾Buffer

by Ricardo FernƔndez Serrata

Version 1 (May 17, 2021)

Download (18 downloads)

This improves performance when using an array as a FIFO queue buffer. Instead of using Add(x, -1) and Remove(x, 0), it keeps the array at a fixed length and replaces values cyclically kinda like a "sawtooth waveform".

This is a relief for AM interpreter, ART/Dalvik/JVM and the CPU, because they don't have to decide about how, when or where to shift the offset of the internal buffer (or maybe even move data) and don't need to do awkward memory allocation, reallocation and deallocation.

But the performance improvement is actually noticeable when using a statically and strongly typed language, especially when it's a compiled language. In AM (dynamically typed interpreted lang), this is generally not useful, unless you want to squeeze max performance out of AM.

The 2nd loop shouldn't be necessary, but I used it because it was easier and I tried MULTIPLE different ways of avoiding that loop.

The "length" var is necessary if you want to resize the buffer. But I haven't coded a proper resizing mechanism. If you increase the size, more "room" will be made for new values instead of old values. If you decrease the size, original new values will be ignored instead of old values. The proper way of resizing requires the internal buffer to use reversed indexing.

I could have used a ternary conditional instead of "%" operator because values are never added as a bulk, but conditional reset is more prone to bugs and executes branch operations which could be dramatically slower than "%" op.

ā„¹ en.wikipedia.org/wiki/Circular_buffer

4.5 average rating from 2 reviews

5 stars
1
4 stars
1
3 stars
0
2 stars
0
1 star
0
Reports
0

Rate and review within the app in the Community section.