When to require a module?

I thought I remembered reading somewhere that it’s better to require a module just before you need it, but for the life of me I can’t find it now. I’ve taken the lazy way out, requiring modules I need at the top of my modules:

local Utility = require("Utility")  
...  
local function foo()  
 local b = Utility.getB()  
 -- do something with b  
end  

Would it be better to write the above like this, and if so, why?

local function foo() local Utility = require("Utility") local b = Utility.getB() -- do something with b end [import]uid: 58455 topic_id: 27173 reply_id: 327173[/import]

In theory, with the second version, wouldn’t the module have to be loaded upon each function call? That would be quite a performance hit. Also, anything inside that module would not be accessible to any other function outside that one, since it’s local to that function.
[import]uid: 6084 topic_id: 27173 reply_id: 110322[/import]

Yes, that makes sense to me. Not sure if/where I read that now. :-/

I just wrote a little test and the method you thought would be faster was, in fact, more than twice as fast.

The functions I wrote were trivial, and perhaps the speedup gains wouldn’t be so dramatic were real work being done, but I don’t yet see a reason to prefer local requires over module level requires at the top. [import]uid: 58455 topic_id: 27173 reply_id: 110339[/import]

You were probably trying to remember the optimizations possible by tightening the scope of the variables you’re using to be more “local”. I’m not sure if this applies to requires so much as to variables and how LUA accesses them. [import]uid: 63787 topic_id: 27173 reply_id: 112735[/import]