Hardly 1: table.concatNice()
Code: Select all
@@ -29,15 +29,8 @@
end
function table.concatNice(t, sep, endsep)
- if not endsep then return table.concat(t, sep) end
- local str = ""
- for i, s in ipairs(t) do
- if i == #t and i > 1 then str = str..endsep..s
- elseif i == 1 then str = s
- else str = str..sep..s
- end
- end
- return str
+ if not endsep or #t == 1 then return table.concat(t, sep) end
+ return table.concat(t, sep, 1, #t - 1)..endsep..t[#t]
end
function table.min(t)
old concatNice | proposed replacement | |
Time: | 34.93s | 19.48s |
Edit 2: Updated to fix a bug with single element tables. Time was 18.65s, now 19.48s. Still faster.
Hardly 2: the previously mentioned, buggy table.orderedPairs()
The current four function set is copied verbatim from the Sorted Iteration page at lua-users.org and is truly appalling. Included in the patch is a slightly tweaked version of my replacement as well as the removal of repeated tests in the comparison function. Benchmarks of iteration through a table of numbers using for loops:
lua-users.org's version (100,000 element table) | proposed replacement (10,000,000 element table) | |
Time (rounded): | 9:35 | 1:18 |
Hardly 3: util.factorial()
Code: Select all
@@ -1916,11 +1885,11 @@
end
function util.factorial(n)
- if n == 0 then
- return 1
- else
- return n * util.factorial(n - 1)
+ local f = 1
+ for i = 2, n do
+ f = f * i
end
+ return f
end
function rng.poissonProcess(k, turn_scale, rate)
old factorial | proposed replacement | |
Time (rounded): | 8:43 | 1:08 |
Max memory usage: | > 15MB | < 750kB |
Edit: I just double checked and see that Lua doesn't have built-in bignum support (seriously?). I'm not sure whether actually using large numbers would make this one closer.
Patch:
This patch replaces the horrible, buggy table.orderedPairs() and includes the improvements to table.concatNice() and util.factorial() presented above.