Skip to content

Instantly share code, notes, and snippets.

@bytejon
Last active August 30, 2025 21:06
Show Gist options
  • Select an option

  • Save bytejon/f38c4e0f73aaee536316ce0adaf96c99 to your computer and use it in GitHub Desktop.

Select an option

Save bytejon/f38c4e0f73aaee536316ce0adaf96c99 to your computer and use it in GitHub Desktop.
A small utility for dequeuing items from an array (FIFO) but with the speed of a stack-based O(1) removal. Shifting is avoided with swaps. The queue is assumed to not add anymore items.
-- queue: (assumed to not add anymore items mid-dequeue)
-- length: the initial length of the queue
local function fastDequeue(queue, length)
local k = #queue
local i = math.min(k, length - k + 1)
queue[i], queue[k] = queue[k], queue[i]
local v = queue[k]
queue[k] = nil
return v
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment