Can it be more efficient by calling table.insert inside the object's init function instead of calling table.insert for every actor object?
Yes, but it probably won't matter too much how efficient your actor initialization and insertion is unless your going to be creating an absurd amount of them, or if you're creating many of them while the game is being played. I really like writing code examples so here's one showing how you can optimize table insertion.
Code: Select all
local test_table_1 = {}
local start = os.clock()
for i = 1, 1000000 do
table.insert(test_table_1, i) --Using table.insert 1,000,000 times.
end
print("Default use of table.insert time taken: ", os.clock() - start, "\n")
local test_table_2 = {}
local insert = table.insert
local start = os.clock()
for i = 1, 1000000 do
insert(test_table_2, i) --Using our localized version of table.insert 1,000,000 times.
end
print("Localized table.insert function time taken: ", os.clock() - start, "\n")
local test_table_3 = {}
local start = os.clock()
for i = 1, 1000000 do
test_table_3[#test_table_3 + 1] = i --Directly placing our values at the end of the table 1,000,000 times.
end
print("Direct insertion without function overhead time taken :", os.clock() - start, "\n")
--[[Default use of table.insert time taken: 0.2400000000000002
Localized table.insert function time taken: 0.20999999999999996
Direct insertion without function overhead time taken : 0.17999999999999972]]
This example shows that even with a million values to be inserted into a table, the difference between the normal way and the fastest way of inserting into a table yields only about 1/20th of a second gain. Pretty negligible for most application, but I think it's good practice to use this method when storing values in a table in love.update or love.draw