Is there any performance value in creating local copies of Lua functions?

后端 未结 2 1547
暗喜
暗喜 2021-01-12 21:08

Is there any value in creating local copies of common Lua functions like print(), pairs() or ipairs()?

Example:



        
2条回答
  •  我在风中等你
    2021-01-12 21:54

    This is an example in Lua Programing Gems:

    Access to external locals (that is, variables that are local to an enclosing function) is not as fast as access to local variables, but it is still faster than access to globals. Consider the next fragment:

    function foo (x)
      for i = 1, 1000000 do
        x = x + math.sin(i)
      end
      return x
    end
    print(foo(10))
    

    We can optimize it by declaring sin once, outside function foo:

    local sin = math.sin
    function foo (x)
      for i = 1, 1000000 do
        x = x + sin(i)
      end
      return x
    end
    print(foo(10))
    

    This second code runs 30% faster than the original one

提交回复
热议问题