How to write efficient code?

Writing efficient and optimized code is a great goal! Like any skill, optimizing code will get easier with practice.

Before diving into complex solutions, let’s highlight the focus of the tips with the foundational goal of all optimization. The goal of optimizing code is to use less system resources to do a certain task. This core concept shows up in virtually every type of optimization. As you said you’ve been developing on Roblox for 4+ years, you probably already know this. But good to keep the core concept in mind, and may help others who read this as well!

Here are a few optimization tips! Some of these tips are basic, while others are more advanced techniques.

  • Use local variables instead of global variables, when possible. Variables take up RAM, so removing variables as soon as possible lets that RAM be re-used quickly for other tasks! Global variables might not ever be de-allocated as long as your script exists, but local variables are removed as soon as the code moves out of the variable’s scope. This frees up RAM sooner.
  • Utilize the Task Scheduler. Tasks are completed in a certain order every frame. For instance, Stepped runs before physics, but Heartbeat runs after the physics simulation. Counter-intuitively, yielding functions like Stepped:Wait() and task.wait() (which waits for Heartbeat) help make code more efficient by ensuring the next lines of code run at the right point in the frame. Additionally, while that script is waiting, other scripts can be running in the background. (Notably, RenderStepped:Wait() is super useful to ensure client-side visual updates, like GUI changes, change at the beginning of the frame!)
  • Use multithreading. Within the last few years or so, Roblox released support for multithreading! Parallel Luau allows multiple scripts to run simultaneously, instead of rapidly switching between scripts. Place Scripts within Actors (a type of Model) and use task.desynchronize() to tell the code, at that point, to start multithreading. However, some functions are not compatible with multithreading, so use task.synchronize() to return the script’s thread to serial instead of parallel. In my opinion, Actors work best if you have a lot of “entities” like enemies, NPCs, or item pickups like coins or power-ups!

I hope these tips could be of help!

1 Like