[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: looking for a better idiom
- From: "J.Jørgen von Bargen" <jjvb.primus@...>
- Date: Sat, 24 Apr 2010 16:53:02 +0200
Hi, folks
I'm looking for a better idiom for
-- initial
local lookup={}
--
for item in item_source() do
-- vv this is the uggly code
local data=lookup[item] or {}
lookup[item]=data
-- ^^ this is the uggly code
-- do something more with data, e.g.
data.set=true
data.count=(data.count or 0)+1
--
end
(Where item_source will return about 20 different items about 1000 times
in random order)
I have replaced it with
local function ta(t,a)
local n={}
t[a]=n
return n
end
-- vv better code
local data=lookup[item] or ta(lookup,item)
-- ^^ better code
eliminating multiple assigns to lookup[item], which already gave me a
speedup of about 11%.
Any suggestions to make it even faster or prettyer (and without a
function call?)
Regards Jørgen
PS: This is not the real code, but I come across this quite often and
like to do it the best way.