Is it a bad practice to do this?

I have been using this method for a year now to clean up my code and put the not so important and less interesting functions at the bottom of my scripts and put all the important stuff at the top
image

But i have started to wonder if using this method can lead to anything bad such as more memory usage or performance impact due to these functions now being seen as global variables (which iirc use more memory).

So is it fine for me to use this method or should i switch to “local function X()”

image

1 Like

It’s good to be aware of performance concerns, but you always have to balance that with code quality concerns. Some code is performance critical, meaning it’s performance directly impacts the quality or even the success of your project. Most code is not. You should identify which parts of your code are performance critical and ensure they are fast enough. Globals vs locals is mostly a “micro optimization”, meaning it usually doesn’t massively impact performance. If you spend a lot of time and effort - or sacrifice code quality - just to make non- performance critical code run 5% faster then, that’s all wasted because it doesn’t matter.

So to answer your question: no, don’t switch to local function foo() end unless you have to. Structuring your code in a top-down manner is not uncommon and if it makes your code more readable then it’s 1000000% worth it for a tiny slow down. If you absolutely have to, then consider declaring all your functions near the top of the script and defining them at the bottom. That way you get the best of both worlds. E.g.

--Declare these variables as local variables in the scope of the script
local foo, bar, interestingFunction --this can just be a huge one-liner that's quick to scroll past

function interestingFunction()
    foo()
    bar()
end

--Boring helper functions here
--Actually define the functions later on to avoid cluttering the top of the script
function foo() end
function bar() end

Alternatively you can put a do end block right after the declarations and define the functions in there. Any editor worth using will allow you to collapse the do end block to hide the clutter.

1 Like