Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- define map function (pretending it's default in lua)
- local function map(t, f) for _, v in pairs(t) do f(v) end end
- -- "randomTable" with 10,000 elements (numbers)
- local randomTable = (function()
- local acc = {}
- for i=1, 10000 do
- table.insert(acc, i)
- end
- return acc
- end)()
- local function mapAnonymous()
- map(randomTable, function(element)
- io.write(element .. ' ')
- end)
- print()
- end
- local function mapDefined()
- local function printElement(element)
- io.write(element .. ' ')
- end
- map(randomTable, printElement)
- print()
- end
- local function pairsLoop()
- for _, element in pairs(randomTable) do
- io.write(element .. ' ')
- end
- print()
- end
- local results = {
- mapA = 0;
- mapB = 0;
- pairs = 0;
- tests = 0;
- }
- local function test()
- -- for speed measurement
- local oldTime, newTime
- -- mapping (with anonymous function)
- oldTime = os.clock()
- mapAnonymous()
- newTime = os.clock()
- results.mapA = results.mapA + (newTime - oldTime)
- -- mapping (defined function)
- oldTime = os.clock()
- mapDefined()
- newTime = os.clock()
- results.mapB = results.mapB + (newTime - oldTime)
- -- pairs
- oldTime = os.clock()
- pairsLoop()
- newTime = os.clock()
- results.pairs = results.pairs + (newTime - oldTime)
- results.tests = results.tests + 1
- end
- local function averageResults()
- for i,v in pairs(results) do
- if i ~= 'tests' then
- results[i] = v / results.tests
- end
- end
- end
- local function printResults()
- print('Mapping (anonymous function):', results.mapA)
- print('Mapping (defined function):', results.mapB)
- print('Using Pairs:', results.pairs)
- end
- test()
- test()
- test()
- test()
- test()
- test()
- test()
- test()
- test()
- test()
- averageResults()
- printResults()
- --[[ results of 5 tests
- Mapping (anonymous function): 0.0341
- Mapping (defined function): 0.0302
- Using Pairs: 0.0287 <-- winner
- Mapping (anonymous function): 0.0329
- Mapping (defined function): 0.0276 <-- winner
- Using Pairs: 0.0315
- Mapping (anonymous function): 0.0384
- Mapping (defined function): 0.0344
- Using Pairs: 0.031 <-- winner
- Mapping (anonymous function): 0.0322
- Mapping (defined function): 0.0416
- Using Pairs: 0.0253 <-- winner
- Mapping (anonymous function): 0.0448
- Mapping (defined function): 0.0262
- Using Pairs: 0.0259 <-- winner
- ]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement