Best place to localise math methods

Hi been wondering this for a while, as some of you should already know it best for performance to localise math functions/methods. Like so: local rand = math.random

My question is it best for performance to localise within every function that it uses or just once for all functions?

Within every function

 local function randomObject()   
 local rand = math.random  
 local randomObject = objects[rand(#objects)]  
 return randomObject  
 end   

Or Outside of function

  
local rand = math.random  
 local function randomObject()   
 local randomObject = objects[rand(#objects)]  
 return randomObject  
 end   

Any insight is appreciated. [import]uid: 118379 topic_id: 26253 reply_id: 326253[/import]

Localizing outside of the function is cleaner, that way multiple functions can use it. And you only need to create the variable once. [import]uid: 9840 topic_id: 26253 reply_id: 106415[/import]

Thanks, I think i was just reading your tutorial on Facebook intergration actually on your website, so double thanks.

Still a little confused on what I need to do on facebook side setup. Im sure il get there, facebook info sucks on here. [import]uid: 118379 topic_id: 26253 reply_id: 106417[/import]

Localizing functions is an optimization that’s not always worth the trouble. It’s most beneficial for tight loops that refer to a function, like an enterFrame event. In most cases I wouldn’t bother.

However, if you think about the work you’re trying to avoid by localizing the function – a lookup to the global environment – and keep in mind that the process of localizing the function itself has to do this work, that should help you decide whether to localize inside or outside a function.

This

[lua]local rand=math.random
for i=1,1000000 do
local x = rand(100)
end[/lua]

is faster than this

[lua]for i=1,1000000 do
local rand=math.random
local x = rand(100)
end[/lua]

But we’re talking about milliseconds. In a program with a lot of other things going on, the little things add up.
[import]uid: 44647 topic_id: 26253 reply_id: 106420[/import]

Yep thats covered all my questions, just want the fastest method. Thanks chaps. [import]uid: 118379 topic_id: 26253 reply_id: 106422[/import]