# How to get the length of a dictionary.

• I recently found out that you cannot get the length of a dictionary with the # method. In order to calculate the length of a table you have to use some kind of loop. On the discord, where I was discussing the issue, kingdom5, TheeDeathCaster, and me, Phlegethon5778 each proposed a function designed to get the length of an array. I then performed a test and took the average results to see who's method was the most efficient. Here is the test:

``````local function returnAverage(array)
local count = #array
local total = 0
for i,v in pairs(array) do
total = total + v
end
total = total / count
end

local dict = {}

for i = 1, 1000 do
dict["hello"..i] = i
end

local numberResults = {
["Phlegethon5778"] = {};
["kingdom5"] = {};
["TheeDeathCaster"] = {};
}

for i = 1, 100 do

wait(.5)

local timeOne = tick()

local function dictLengthFinder(tbl)
local next = next
local a, b = next(tbl)
local i = a and 1 or 0

while a do
b = next(tbl,next(tbl,next(tbl,next(tbl,next(tbl,next(tbl,next(tbl,next(tbl,next(tbl, next(tbl, a))))))))))
if b then
i = i + 10
a = b
else
while a do
a = next(tbl, a)
i = i + 1
end
end
end
return i
end

for i = 1, 1000 do
dictLengthFinder(dict)
end

timeTwo = tick() - timeOne

wait(.5)

timeThree = tick()

local function dictLengthFinderTwo(Table)
local Length = 0
for i in next, Table do
Length = Length + 1
end
return Length
end

for i = 1, 1000 do
dictLengthFinderTwo(dict)
end

timeFour = tick() - timeThree

wait(.5)

local timeFive = tick()

local function dictLengthFinderThree(tbl)
local length = 0
for i,v in pairs(tbl) do
length = length + 1
end
return length
end

for i = 1, 1000 do
dictLengthFinderThree(dict)
end

local timeSix = tick() - timeFive

table.insert(numberResults["Phlegethon5778"], timeSix)
table.insert(numberResults["TheeDeathCaster"], timeFour)
table.insert(numberResults["kingdom5"], timeTwo)

wait(.5)

end

for i,v in pairs(numberResults) do
print(i.."'s method: ", returnAverage(v))
end
``````

Here are the results:

TheeDeathCaster's method: 0.31946294307709
Phlegethon5778's method: 0.31631227970123
kingdom5's method: 0.24586079835892

I hope this interested you and provided an efficient method to get the length of a dictionary. Have a great day scripting! Phlegethon5778

• @Phlegethon5778 should be in the tutorials section m8

• @incapaz No.

• Using `next` over `pairs` provides absolutely no performance bonus.
As for TheeDeathCaster's method, that was simply retarded.

• @Link150 Also that was a bad benchmark. By starting the chronometer before the function definitions, you've included the time necessary to create the closures into the results.

• @Link150 Thank you for pointing that out. I would like to say that I also did tests with the function definitions outside of the loop and there was a similar ratio of times. Because studio has been rather trash lately all my results have been different so I am waiting for a fix before testing again.