# Untitled

a guest
Nov 1st, 2018
562
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. function test_tableremove(mylist)
2.     for i=#mylist,1,-1 do
3.         if mylist[i] == 13 then
4.             table.remove(mylist, i)
5.         end
6.     end
7. end -- func
8.
9. function test_mitch(mylist)
10.     -- NOTE: This is a messy, hardcoded version of my algorithm, for test-purposes.
11.     -- Go to https://stackoverflow.com/a/53038524/8874388 for the actual, clean version.
12.     local j, n = 1, #mylist;
13.
14.     for i=1,n do
15.         local value = mylist[i]
16.         if value ~= 13 then -- Keep everything except "13"
17.             -- Move i's kept value to j's position, if it's not already there.
18.             if (i ~= j) then
19.                 mylist[j] = mylist[i];
20.                 mylist[i] = nil;
21.             end
22.             j = j + 1; -- Increment position of where we'll place the next kept value.
23.         else -- Delete "13"
24.             mylist[i] = nil;
25.         end
26.     end
27. end
28.
29. function build_tables()
30.     local tables = {}
31.     for i=1, 10 do
32.       tables[i] = {}
33.       for j=1, 2000000 do -- 2 million items
34.         tables[i][j] = (j % 5 == 0 and 13 or 100) -- put a "13" (deleted) in every 5th item, otherwise "100" (kept)
35.       end
36.     end
37.
38.     return tables
39. end
40.
41. function time_func(func, name)
42.     local tables = build_tables()
43.     time0 = os.clock()
44.     for i=1, #tables do
45.         func(tables[i])
46.     end
47.     time1 = os.clock()
48.     print(string.format("[%10s] elapsed time: %.3f\n", name, time1 - time0))
49. end
50.
51. time_func(test_mitch, "mitch")
52. time_func(test_tableremove, "table.remove")
53. time_func(test_mitch, "mitch")
54. time_func(test_tableremove, "table.remove")