1

A function f() returns multiple values, which are to be fed into a second function g(). I cannot change f(), but I can change g() and all calls to it. I'm wondering if it's possible to say which variant performs best? What does it depend on?

  • Function header with one table argument

    function g(arg)
    --code
    end
    

    and function call with table constructor

    g({f()})
    
  • Function header with variable number of arguments

    function g(...)
    --code
    end
    

    and regular function call

    g(f())
    
  • Function header with multiple variables (assuming number of f() return values is known)

    function g(x, y, z)
    --code
    end
    

    and regular function call

    g(f())
    
  • A completely different variant?

3
  • 3
    You'll have to define "performs best" and measure. Commented Aug 13, 2024 at 0:31
  • 4
    Are you really using Lua 5.0?? Commented Aug 13, 2024 at 0:32
  • Judging by later Lua versions, I would expect the table argument to be the slowest (it requires first moving the vararg from the stack to a table on the heap; note also that this is lossy in case of trailing nils), the variadic function to be the second slowest, and the function with the known number of arguments to be the fastest (it requires keeping track of vararg info, such as length). But measure. Commented Aug 13, 2024 at 0:32

1 Answer 1

1

First of all, beware of premature optimization. If g(f()) calls are relatively infrequent then the difference might be negligible.

Next, creating an extra table takes time, so option (1) is always slower than (3).

Concerning option (2), it really depends on what g() actually does with the arguments. local args = {...} is an equivalent of option (1), while local x, y, z = ... is the same as (3).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.