Circular buffer operation costs 2026-10-18
With storage allocated in advance, each successful insertion, removal,
peek, size, and full/empty check uses worst-case time complexity in Big O notation. This assumes constant-cost indexed array access, bounded machine word index arithmetic and fixed-cost scalar item reads and writes. Each operation touches a bounded number of slots and fields regardless of and ; no shifting, scanning or resizing occurs. Rejected operations also take constant work. Producing a copy of all live items takes work under the same scalar-cost assumptions.The preallocated array occupies scalar slots plus constant bookkeeping. Allocation and any initial slot construction are separate setup costs. Copying a large item, running an expensive destructor or callback, allocating an item, or growing a dynamic array changes the operation cost and must be charged separately. The bound is worst-case structural work, with no need for amortized analysis, and says nothing about a measured wall-clock deadline.
These formulas describe sequential calls. Wrapping array indices implies neither atomic operations nor safe access from multiple software threads. Publication of an item's contents and reuse of its slot require a protocol justified under the relevant memory model, including any necessary acquire-release synchronization. The kernel documentation discusses barriers under explicit producer/consumer restrictions; Boost's documentation separately requires mutual exclusion for shared access involving writes. Neither property follows merely from choosing a circular buffer.[ref]
Circular Buffers by David Howells and Paul E. McKenney. David Howells and Paul E. McKenney, Circular Buffers, Using memory barriers with circular buffers; The producer; The Consumer: explicit synchronization and ordering requirements
[ref]Implementation. Jan Gaspar, Boost.Circular Buffer, Implementation, Thread-Safety: shared access involving a writer requires mutual exclusion
Dynamic array 2026-10-18
A dynamic array is an array whose backing storage can grow as entries are appended. Dynamic array doubling is one growth policy with a deterministic amortized analysis.
Dynamic array doubling Created 2026-10-18 Updated 2026-10-31
Consider a dynamic array holding fixed-size entries. Its size is the number of occupied slots and its capacity is the number of allocated slots. Start with , . The only operation is append: if , allocate a new array of capacity , copy the existing entries, and release the old array; then write the new entry and increase by one. There is no reserve operation, deletion or shrinking in this model.
Count one unit for writing the new entry and one unit per existing entry copied during resizing. Thus the th append has actual cost without resizing and when the old capacity is full. Copying an entry, including its read and write, is one counted action. Allocation, deallocation, index arithmetic operations and the initial one-slot allocation are outside this exact count. If these add only a constant per ordinary append and a linear cost per resize, the Big O notation conclusions still hold, with different constants; costly entry copies require their own cost model.
The first ten costs are . For example, append copies eight entries and writes one, so . At that point the capacity becomes , but the total cost of all nine appends is only .
For , the final capacity is . Every earlier capacity was copied once. This geometric series sums to , including the empty sum when . Therefore aggregate analysis gives the exact totalConsequently , so append has amortized cost in Big O notation for every prefix from this empty initial state. The values being appended do not affect the count. In contrast, an append to a full dynamic array with entries costs : its worst-case cost is , and actually grows linearly along full-capacity states. A bound on total work does not promise a constant response time for each call.
Individual append costs and cumulative work under dynamic array doubling
. The spikes include every copied entry and the new write. At append 33 the actual cost is 33; at append 64 the total cost is 127. Every prefix lies below the line . Details.The same policy controls computer memory: after each completed append, for , so fewer than slots are unused. This is a bound on the retained backing array, with fixed-size slots. During a resize from full capacity to , a copying implementation can temporarily hold both arrays, totalling allocated slots before releasing the old one. Thus the retained-capacity bound does not bound this temporary peak by twice the live size. Allocator metadata and separately allocated objects are additional computer memory costs.
The geometric series is the source of the efficiency. If capacity instead increases by one each time, the same count becomes , a quadratic total. Dynamic array doubling buys a linear total with bounded spare capacity, even when the final length is unknown.
Jonas Almström Duregård Created 2026-10-14 Updated 2026-11-05
Jonas Almström Duregård is a computer scientist and a coeditor, with Peter Ljunglöf and Alex Gerdes, of Data Structures and Algorithms edited by Peter Ljunglöf and others. The book connects data structures with algorithms that operate on them, including linked lists, dynamic arrays and binary trees. Its organization illustrates the distinction between an interface's promised operations and the representation used to implement them.[ref]
Homepage: www.chalmers.se/en/persons/almstroj/
Store characters in a mutable dynamic array. Its length is maintained by the collection, giving constant-time The representation invariant requires a nonnull private dynamic array containing a finite sequence of characters, with its internal collection invariant maintained by the library. The abstraction function isInsertion allows the end position and shifts the suffix right; deletion returns exactly the removed character and shifts the suffix left.
size.class DocImpl extends Doc {
private val text = scala.collection.mutable.ArrayBuffer.empty[Char]
def insert(x: Char, pos: Int): Unit = {
require(0 <= pos && pos <= text.length)
text.insert(pos, x)
}
def delete(pos: Int): Char = {
require(0 <= pos && pos < text.length)
text.remove(pos)
}
def read(pos: Int): Char = {
require(0 <= pos && pos < text.length)
text(pos)
}
def size: Int = text.length
}read leaves the abstract state unchanged. size equals the abstract sequence length in time complexity. Indexed reads are also constant time; insertion and deletion may take linear time, which the question permits.Use a history dynamic array and a cursor between elements. If the cursor is behind the history's end, The representation invariant is , with history exactly the prefix already consumed from the original source. The logical unread sequence is the history suffix starting at
next replays history; otherwise it pulls a new element from the source. prev moves the cursor left and returns the element crossed, so prev followed by next returns the same element twice and restores the cursor.def genBiIter[T](it: Iter[T]): BiIter[T] = new BiIter[T] {
private val history = scala.collection.mutable.ArrayBuffer.empty[T]
private var pos = 0
def hasPrev: Boolean = pos > 0
def hasNext: Boolean = pos < history.length || it.hasNext
def next(): T = {
if (pos < history.length) {
val v = history(pos); pos += 1; v
} else if (it.hasNext) {
val v = it.next()
history += v; pos += 1; v
} else {
throw new NoSuchElementException("BiIter.next")
}
}
def prev(): T = {
if (!hasPrev) throw new NoSuchElementException("BiIter.prev")
pos -= 1
history(pos)
}
}pos, followed by the source's remaining sequence. The logical backward history is the prefix before pos. Every operation preserves this model, including alternating backward and forward moves after source exhaustion.This bidirectional iterator uses storage after consuming distinct source elements. Replay and backward moves take constant time; appending has amortized time complexity under the usual dynamic array model. The input iterator must not be advanced separately.Use an immutable list as private storage and cache its length. This makes the data refinement transparent without depending on library-specific dynamic array costs:The representation invariant is , with
class DocImpl extends Doc {
private var chars: List[Char] = Nil
private var length: Int = 0
def size: Int = length
def insert(x: Char, pos: Int): Unit = {
require(0 <= pos && pos <= length)
val parts = chars.splitAt(pos)
chars = parts._1 ::: (x :: parts._2)
length += 1
}
def delete(pos: Int): Char = {
require(0 <= pos && pos < length)
val parts = chars.splitAt(pos)
val old = parts._2.head
chars = parts._1 ::: parts._2.tail
length -= 1
old
}
def read(pos: Int): Char = {
require(0 <= pos && pos < length)
chars(pos)
}
}chars representing the abstract document sequence. splitAt(pos) isolates exactly the prefix before the selected array index-style position. Insertion retains that prefix and the old suffix, placing the new character between them. Deletion returns the old suffix head and retains its tail. Updating the cached length by one preserves the representation invariant. read and size preserve the abstract state.The preconditions permit insertion at the end, including position zero in an empty document, but forbid reading or deleting at the end.A decreased key can violate heap order only against its parent. An inserted entry begins at the next free position and uses the same repair:Here is a sentinel at least as large as every permitted key. One can equivalently write
DecreaseKey(A,i,key):
if i < 0 or i >= A.heap_size:
error "invalid index"
if key > A[i]:
error "key increased"
A[i] = key
while i > 0:
p = Parent(i)
if A[p] <= A[i]:
return
swap A[p], A[i]
i = p
Insert(A,key):
ensure capacity for A.heap_size+1 entries
i = A.heap_size
A.heap_size = A.heap_size+1
A[i] = +infinity
DecreaseKey(A,i,key)key directly into the new entry and run the upward loop, avoiding any sentinel representation.At every upward swap, the smaller key moves above its larger parent; the displaced parent remains no larger than the entries below it, as follows from the old heap order. Thus only the new parent edge can be invalid. At most one parent comparison is needed per level, with no scan of siblings. Both operations take time in the usual range, or uniformly including tiny heaps and large .
The heap-operation bound assumes space for the inserted entry. A capacity expansion in a dynamic array can cost for that individual insertion; sufficient preallocation avoids it, while geometric capacity growth adds only constant amortized allocation cost per insertion.
class DocImp extends Doc {
private val data = scala.collection.mutable.ArrayBuffer.empty[Char]
def insert(pos: Int, ch: Char): Unit = {
require(0 <= pos && pos <= data.length)
require(data.length < Int.MaxValue)
data.insert(pos, ch)
}
def delete(pos: Int): Char = {
require(0 <= pos && pos < data.length)
data.remove(pos)
}
def apply(pos: Int): Char = {
require(0 <= pos && pos < data.length)
data(pos)
}
def length: Int = data.length
}The representation invariant is that
data is a well-formed private dynamic array of at most Int.MaxValue characters. Its abstraction function is the buffer's character sequence. Initialization is empty; insertion and removal at the checked position implement exactly the required sequence edits, and the queries do not modify it.length and indexing are because a dynamic array stores its used length and supports address arithmetic for indexed access. An insertion or deletion at position in a document of length shifts entries; insertion can additionally resize the backing storage, giving amortized time and worst-case for one operation. Deletion is with an additional constant term.Building a document by appending the characters of a length- string costs amortized time, since geometric capacity growth copies a total of only entries. Thus this implementation does not have the quadratic append behavior of repeated immutable-string concatenation. A known final length can also be reserved in advance. The bounds use the usual amortized analysis of a dynamic array.[ref]
Performance Characteristics of Scala 2.13 collections. Mutable sequence table: ArrayBuffer constant indexed access and amortized constant append
Official operation-cost tables for sequence and map implementations. The mutable sequence table identifies constant indexed access and amortized constant append for dynamic arrays; the explanation distinguishes constant, effectively constant, amortized constant, logarithmic and linear bounds.
