确定一个数字是否包含在给定列表中的不同方法

哪种方法更快速:检查一个数字是否等于另一个,还是在表格中查找该数字?

我有一个程序,从服务器发送的命令以数字形式接收。命令频繁发送:每秒钟从1个到30个以上。某些命令会被忽略,而其他命令会触发各种事件。通过执行以下操作来确定触发哪个事件更好:

function incoming_integer(n)
  if n == 33 then
    print('a')
  elseif n == 44 then
    print('b')
  elseif n == 567 then
    print('c')
    ... (实际列表偶尔相当长:超过十个有效数字)
  end
end

还是这个:

functions = {
  [33] = function() print('a') end,
  [44] = function() print('b') end,
  [567] = function() print('c') end,
  ...
}
relevant_commands = {[33]= true, [44]=true, [567]=true ...}
function incoming_integer(n)
  if relevant_commands[n] then
    functions[n]()
  end
end

有没有一种方法更有效率的点?如果命令被作为字符串发送,会怎样?

点赞
用户88888888
用户88888888

如果你想用返回的数字来触发不同的事件,我会这样用...

function trigger( value )
if ( value == "..." ) then
    triggerThis()
elseif ( value == "..." ) then
    triggerElse()
    -- 以此类推
    end
end

function incoming_integer(n)
if ( n ) then -- 检查变量是否进入以防止错误
    trigger( n )
else
    alert( "noop, 这里没有什么" )
    end
end
2014-10-16 10:06:01
用户88888888
用户88888888

也许你可以尝试使用键。仅为示例,并未测试过。 http://lua-users.org/wiki/TablesTutorial

table = { [33]="a", [44]="b", [567]="c" }

function onCall( value ) -- 如果为 33
    if ( table[value] ) then
        return( table[value] ) -- 如果存在返回 a
    end
end

onCall( 33 ) -- 现在它将在表中搜索并获取键

编辑:您可以像数字一样命名触发的函数,这样可以直接触发它们。这将节省很多时间!

2014-10-16 11:14:16
用户2279620
用户2279620

针对您的吞吐量,我建议使用任何一种机制的开销可能是可以忽略不计的。我对字符串和数字键的查找表开销进行了非常快速而简单的测试。见下文。即使有大量键和高命中率,我也难以在我能找到的最慢的机器上获得超过1微秒的开销。

f = {}
function incoming_integer(n)
    local t = f[n]
    return t and t()
end

SIZE = 10000
RAN = 20000
REPEAT = 10000000

for i =1,SIZE do
    --f[math.random(RAN)] = function() return "z" end
    f[tostring(math.random(RAN))] = function() return "z" end
end

tm = os.time()
for i = 1,REPEAT do
    --math.random(RAN)
    tostring(math.random(RAN))
end
print(os.difftime(os.time(),tm))

tm = os.time()
for i = 1,REPEAT do
    --incoming_integer(math.random(RAN))
    incoming_integer(tostring(math.random(RAN)))
end
print(os.difftime(os.time(),tm))
2014-10-16 12:20:19
用户4162169
用户4162169
functions = {[33] = function() print('a') end, etc...}

setmetatable(functions, {__index = function() return function() end end}) -- 如果找不到定义的函数,则返回空函数

使用方法:

functions[32]() -- 不作处理
functions[33]() -- 执行定义的函数
2014-10-20 20:49:32