Skip to content

Commit 90567ff

Browse files
committed
perf: respect depth limit in countCycles
This change modifies countCycles to respect the depth parameter and stop recursing once the depth limit is reached, improving performance for deep table structures. Fixes #57
1 parent 1c56309 commit 90567ff

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

inspect.lua

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,17 +154,19 @@ local function getKeys(t)
154154
return keys, keysLen, seqLen
155155
end
156156

157-
local function countCycles(x, cycles)
157+
local function countCycles(x, cycles, depth)
158158
if type(x) == "table" then
159159
if cycles[x] then
160160
cycles[x] = cycles[x] + 1
161161
else
162162
cycles[x] = 1
163-
for k, v in rawpairs(x) do
164-
countCycles(k, cycles)
165-
countCycles(v, cycles)
163+
if depth > 0 then
164+
for k, v in rawpairs(x) do
165+
countCycles(k, cycles, depth - 1)
166+
countCycles(v, cycles, depth - 1)
167+
end
168+
countCycles(getmetatable(x), cycles, depth - 1)
166169
end
167-
countCycles(getmetatable(x), cycles)
168170
end
169171
end
170172
end
@@ -327,7 +329,7 @@ function inspect.inspect(root, options)
327329
end
328330

329331
local cycles = {}
330-
countCycles(root, cycles)
332+
countCycles(root, cycles, depth)
331333

332334
local inspector = setmetatable({
333335
buf = { n = 0 },

inspect.tl

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,17 +154,19 @@ local function getKeys(t: table): {any}, integer, integer
154154
return keys, keysLen, seqLen
155155
end
156156

157-
local function countCycles(x: any, cycles: {any:integer}): nil
157+
local function countCycles(x: any, cycles: {any:integer}, depth: integer): nil
158158
if x is table then
159159
if cycles[x] then
160160
cycles[x] = cycles[x] + 1
161161
else
162162
cycles[x] = 1
163-
for k,v in rawpairs(x) do
164-
countCycles(k, cycles)
165-
countCycles(v, cycles)
163+
if depth > 0 then
164+
for k,v in rawpairs(x) do
165+
countCycles(k, cycles, depth - 1)
166+
countCycles(v, cycles, depth - 1)
167+
end
168+
countCycles(getmetatable(x), cycles, depth - 1)
166169
end
167-
countCycles(getmetatable(x), cycles)
168170
end
169171
end
170172
end
@@ -327,7 +329,7 @@ function inspect.inspect(root: any, options: inspect.Options): string
327329
end
328330

329331
local cycles = {}
330-
countCycles(root, cycles)
332+
countCycles(root, cycles, depth)
331333

332334
local inspector = setmetatable({
333335
buf = { n = 0 },

0 commit comments

Comments
 (0)