Quantcast Why declare local versions of functions? - WoWInterface
Thread Tools Display Modes
05-17-19, 05:54 AM   #1
Pindrought
A Defias Bandit
Join Date: May 2019
Posts: 2
Why declare local versions of functions?

I've been looking at source code for some existing addons, and I noticed something that doesn't make sense to me.


Why do they do this for all their functions?

Code:
local _G = _G
local abs = abs
local assert = assert
local collectgarbage = collectgarbage
local date = date
  Reply With Quote
05-17-19, 06:03 AM   #2
myrroddin
A Molten Giant
 
myrroddin's Avatar
AddOn Author - Click to view addons
Join Date: Oct 2008
Posts: 991
If the addon uses or calls those functions a lot, like in a loop that runs hundreds or thousands of times, or if the functions are tied to event handlers that fire all the time, then creating local references will trade RAM/memory for CPU efficiency.
Lua Code:
  1. -- psuedocode example
  2. local n = 1
  3. do
  4.     print("The value of n is: ", n)
  5.     n = n + 1
  6. until n == 100000
print will be called 100,000 times, each one a lookup on the global table. That is not efficient.
Lua Code:
  1. local print = print -- looked up once, and kept in memory
  2. local n = 1
  3. do
  4.     print("The value of n is: ", n)
  5.     n = n + 1
  6. until n == 100000

Last edited by myrroddin : 05-17-19 at 12:58 PM. Reason: missed incrementer for n
  Reply With Quote
05-17-19, 06:20 AM   #3
Pindrought
A Defias Bandit
Join Date: May 2019
Posts: 2
Originally Posted by myrroddin View Post
If the addon uses or calls those functions a lot, like in a loop that runs hundreds or thousands of times, or if the functions are tied to event handlers that fire all the time, then creating local references will trade RAM/memory for CPU efficiency.
Lua Code:
  1. -- psuedocode example
  2. local n = 1
  3. do
  4.     print("The value of n is: ", n)
  5. until n == 100000
print will be called 100,000 times, each one a lookup on the global table. That is not efficient.
Lua Code:
  1. local print = print -- looked up once, and kept in memory
  2. local n = 1
  3. do
  4.     print("The value of n is: ", n)
  5. until n == 100000
Such a good explanation! Thank you!
  Reply With Quote

WoWInterface » Developer Discussions » Lua/XML Help » Why declare local versions of functions?

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off