What types of code cost a lot of performance?

As a developer I think it’s important that we know how much performance we’re using so our games run smoothly for our players.

If there’s anyone who’d like to post what types of code they noticed or just know use up a lot of server/client performance, then by all means please post here I’d like to know what types of code I should avoid using too much.

I’d also like to know what kind of things create memory leaks.

1 Like

Here are some things you should keep in mind:

  • Avoid using loops that run 10000x times in a single thread
  • Always clean up after an object or code has finished its use
  • Reduce server - Client and Client - Server invocations
2 Likes

When you say clean up, what do you mean by that? If I create a variable, do I have to clean that? I know tables/objects need to be cleaned after they’re finished, but other types of code would be what?

If you write it correctly, it may still have a big deal on performance. You just have to write the code, and see if you can optimize the code any further. For example, if you were to so this:

local Number = 1
while true do
    if Number == 100 then break
    Number = Number + 1
    wait(1)
    print("foo")
end

You can optimize it my doing this:

for i = 1, 100 do
    wait(1)
    print("foo")
end

Removing all references to an object (like a table or an instance that’s been :Destroy()'ed) will cause it to be removed from memory by lua’s garbage collector.

1 Like

I think any optimizations in a loop are helpful, even the small ones. I’ll give an example.

while wait() do
    print(Player.Character.HumanoidRootPart.Position)
end
-- vs
while wait() do
    for i = 1, 1000 do
        print(Player.Character.HumanoidRootPart.Position)
    end
end

There’s nothing you can really do to optimize the code in the first loop; however in the second loop, assuming the player isn’t moving too fast, you can just set the player’s position to a variable rather than look up the value every iteration.

->
while wait() do
    local position = Player.Character.HumanoidRootPart.Position
    for i = 1, 1000 do
        print(position)
    end
end

Generally, when you have iterative tasks that rely on static data, you should cache the data into memory so the code is more performant. There are cases where you want the most recent data available so that isn’t possible, but do this whenever you can to make loops more efficient.

This is one I like to highlight since loops are generally where lag starts to factor in. Whether it’s moving lots of parts, or animating lots of players, upscaling requires a good knowledge of how to speed up loops.