Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local sum = 0 -- just for benchmark
- -- insert elements into some object
- local function insert(obj, elem1, elem2, ...)
- -- this function may have 1..inf actual arguments
- if not elem2 and elem1 then
- -- user invoked this function to insert single element
- -- this is the most frequent usage of this function
- -- for the sake of performance we avoid to create a table
- ----------------------------------------------------------------
- -- optimized code for inserting single element (elem1)
- ----------------------------------------------------------------
- sum = sum + elem1 -- this line is just for contrived benchmark
- else -- "else" branch is not being benchmarked
- -- user invoked this function to insert multiple elements
- -- we are creating a table containing named arguments and varargs
- local elems = {elem1, elem2, ...}
- for j = 1, #elems % 8 do
- insert(obj, elems[j]) -- recursive call to insert one element
- end
- for j = #elems % 8 + 1, #elems, 8 do
- local e1, e2, e3, e4, e5, e6, e7, e8 = unpack(elems, j, j + 7)
- ----------------------------------------------------------------
- -- inserting full block of eight elements
- -- (it is faster than inserting 8 elements one-by-one)
- ----------------------------------------------------------------
- end
- end
- end
- local time_start = os.clock()
- for j = 1, 1e8 do
- insert(nil, 1)
- end
- print(os.clock() - time_start)
Advertisement
Add Comment
Please, Sign In to add comment