Last active
July 13, 2021 00:38
-
-
Save Vurv78/2de64f77d04eb409abed008ab000e5ef to your computer and use it in GitHub Desktop.
Faster? id allocation without recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local MaxConcurrent = 512 -- Max concurrent active streams | |
local TopID = 0 -- Current top-most id. | |
local IsSequential = true -- Boost for initial creation when no IDs have been dropped. | |
local OccupiedCount = 0 | |
local Occupied = {} | |
local function register(id) | |
Occupied[id] = true | |
OccupiedCount = OccupiedCount + 1 | |
TopID = id | |
return id | |
end | |
local function allocID() | |
if OccupiedCount >= MaxConcurrent then return end | |
if IsSequential then | |
return register(TopID+1) | |
end | |
local left_until_loop = MaxConcurrent-TopID | |
for i = 1, left_until_loop do | |
local i2 = TopID + i | |
if not Occupied[i2] then | |
return register(i2) | |
end | |
end | |
for i = 1, TopID do | |
if not Occupied[i] then | |
return register(i) | |
end | |
end | |
end | |
local function dropID(id) | |
if Occupied[id] then | |
Occupied[id] = nil | |
OccupiedCount = OccupiedCount - 1 | |
IsSequential = false | |
return true | |
end | |
return false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment