Is this a valid use case for globals?

I find my code being peppered by lots of calls to display.contentWidth and display.contentHeight.

Aside from code aesthetic concerns, it also seemed not optimal to me. So I ran these two test programs:

Program A:

start\_time = os.time()  
for i=1,10000000 do  
 local h = display.contentHeight  
 local w = display.contentWidth  
end  
end\_time = os.time()  
print(end\_time - start\_time)  

Program B:

start\_time = os.time()  
\_G.h = display.contentHeight  
\_G.w = display.contentWidth  
for i=1,10000000 do  
 local h = \_G.h  
 local w = \_G.w  
end  
end\_time = os.time()  
print(end\_time - start\_time)  

Program A took 8 seconds, Program B took just 1 second. A 7-second performance improvement boost for 10M calls doesn’t seem significant to me (still within an order of magnitude). But what’s significant for me is the code readability: _G.h and _G.w are less terse than display.contentHeight and display.contentWidth, respectively.

What do you think? Am I missing reasons why I shouldn’t use _G in this case? [import]uid: 7026 topic_id: 6056 reply_id: 306056[/import]

I had the exact same thought when I was starting out, but I’m very wary of globals, and try to avoid them whenever possible. The compromise I decided on was to set locals at the top of every module I write:

-- Load screen width & height into locals  
local SW, SH = display.contentWidth, display.contentHeight  

Locals are usually faster than globals anyway, and it’s just one line of extra code for each module.
[import]uid: 9659 topic_id: 6056 reply_id: 20798[/import]