Skip to content

Code Rules for GameDev

In this page we'll cover some of the differences between development you've done in the past, and the code you write for game development. Performance is very critical in making sure your game runs smoothly, so we'll talk about a few points.

Tip

"Premature optimization is the root of all evil" [src]. While this is true, and you should be careful about optimizing before you need to, there are some simple patterns you can follow early on to make your life easier in the long run.

Where to be Performant

Realtime Loops

There are a few places in your plugins that has code running in real-time. Some examples of these areas are: Simulate on entities, and the world generator.

In these areas you definitely need to follow the below performance tips.

It's okay to be less performant in loading areas, initialization calls, and most constructors. While this will definitely slow down loading time, it is less critical.

Performance Tips

Don't use foreach

I wrote a big long article about this on my block (zdyn.net)[http://www.zdyn.net], but to put it simply, foreach loops use IEnumerator, which is a class that has to be new'd up. By using foreach you're not only instantiating an object (which is slow), but also giving the garbage collector something extra to clean up. So it's best to avoid them, and use a general for-loop instead.

The proficient programmer might point out that this isn't always the case, which is true, but it's a good rule-of-thumb to follow.

Favor Tasks over Core Loops

If possible, use ITaskScheduler to make something recurring, rather than adding your code to a Simulate. Task manager optimizes to make sure that the user experiences smooth gameplay, and makes sure to give time to tasks that needs tasks. Task manager has the added benefit of guaranteeing to run all tasks on the main thread, which gives you access to all dependencies.

Avoid LINQ

There might be some cases where LINQ is fine, but in general, avoid it. Under the hood, LINQ uses the same mechanisms as foreach, so it can be slow. It's also very easy to get carried away with LINQ and create some bloated code that's very very slow.