Tips when using list #2069
Replies: 1 comment
-
It's something I keep meaning to look at. It's not something PUC Lua does (hence why Cobalt doesn't either), but other implementations like Luau do.
When you use a local tbl, iter = ipairs(list)
local i, v = iter(tbl)
while i ~= nil do
-- Loop body
i, v = iter(tbl, i)
end Despite the fact that With a smarter interpreter, it is possible to handle this better. I believe LuaJIT has a specialisation for this case, and will desugar |
Beta Was this translation helpful? Give feedback.
-
TL; DR
Please note, these suggestions only apply when you are operating large list continuously.
The performance issue will not be significant for most cases.
avoid use
list[#list + 1]
ortable.insert
when appending item.avoid use
ipairs
,pairs
to iterate over a list.I was operating sets of peripherals on serval computers (about 100 peripherals for each computer). After the computer failed multiple times by
Too long without yielding. ComputerCraft may be installed incorrectly.
error, I did this simple benchmark about list performance.list_append_test.lua
results of list append
As we can see in the result, when appending to a array that have size at
100
and above, self maintain a counter when appending a list is almost twice faster than using#
(list length operator), and is 3~4 times faster than usingtable.insert
.After looking into Cobalt's code, I found that internally the
#
operator is using binary search (and linear search in some case?), which is why its that slow. (I don't know if we can cache the length then the operator may be faster.)The next benchmark is about list iterator. Cobalt provides a built-in generator
ipairs
, it can be used infor in
to produce nicer code. But does it also give a nice performance?list_iterator_test.lua
results of list iterator
The result tells us the answer, No! Iterator over using
for i =
is also twice faster thanfor in ipairs
.I do not have a good understanding of how Cobalt internally works. But my guess is
#
operation andipairs
both is implemented in Java, when you invoking them it might increase stack change & usage, and eventually slows your program down.Beta Was this translation helpful? Give feedback.
All reactions