[ANSWERED] A Question about Functions and Using Their Parameters

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
sphyrth
Party member
Posts: 253
Joined: Mon Jul 07, 2014 11:04 am
Contact:

[ANSWERED] A Question about Functions and Using Their Parameters

Post by sphyrth » Wed Nov 04, 2020 11:32 pm

I've been thinking about the way I use variables in functions. Which is more efficient?
#1

Code: Select all

function fff(foo)
   -- use foo directly
   local something = foo + 3
end
#2

Code: Select all

function fff(foo)
  -- use a local variable for it
  local var = foo
  local something = var + 3
end
This may have a case-to-case basis, but my question focused is on efficiency (or maybe it's still negligible even for huge projects. I'll accept the argument about good programming practice. I'll also accept concerns about pass-by-value and pass-by-reference.
Last edited by sphyrth on Thu Nov 05, 2020 10:23 pm, edited 1 time in total.

MrFariator
Party member
Posts: 193
Joined: Wed Oct 05, 2016 11:53 am

Re: A Question about Functions and Using Their Parameters

Post by MrFariator » Thu Nov 05, 2020 3:55 am

In a case like this I think the main concern is how luajit handles it. Any performance gain or penalty is going to be pretty minuscule, I wager.
sphyrth wrote:
Wed Nov 04, 2020 11:32 pm
I'll also accept concerns about pass-by-value and pass-by-reference.
If foo is a table, assigning it into a variable won't change anything. You're still handling a reference, not a copy.

User avatar
ivan
Party member
Posts: 1655
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: A Question about Functions and Using Their Parameters

Post by ivan » Thu Nov 05, 2020 6:24 am

"foo" is already local so there would be no difference.
In fact the second version might be very slightly slower because it allocates more stack space.
As MrFariator mentioned, tables are always references and you can never pass a table as a value.

User avatar
pgimeno
Party member
Posts: 2414
Joined: Sun Oct 18, 2015 2:58 pm

Re: A Question about Functions and Using Their Parameters

Post by pgimeno » Thu Nov 05, 2020 11:29 am

To add to what has already been said, you can examine the bytecode listing to determine that. Here's this test case's bytecode:

Code: Select all

$ luajit -b -l code.lua 
-- BYTECODE -- code.lua:1-4
0001    ADDVN    1   0   0  ; 3
0002    RET0     0   1

-- BYTECODE -- code.lua:6-10
0001    MOV      1   0
0002    ADDVN    2   1   0  ; 3
0003    RET0     0   1
Also, according to my understanding of how the JIT works, if that fragment gets compiled, I expect it won't make any difference in the compiled result whatsoever, as the extra assignment will be optimized out.

Post Reply

Who is online

Users browsing this forum: No registered users and 22 guests