Pre-optimisation in programming is when a programmer tries to design code to be fast and highly optimised before he/she has even written any code. For some less experienced programmer’s this sounds fine, but I know more experienced programmers than myself will know this is a bad idea. So let me tell you how I learnt this and why it’s bad.
For quite a while now I’ve been working on a little C++ game engine as a side project to the various other things going on here at Peripheral Labs. It’s been a way for me to keep up to date with C++ and practice various things in all aspects of game development. But I’ve never gotten very far into the project. I spend ages designing parts of the engine, and then implementing them slowly. After a while I realise the error in my ways and I end up scrapping large parts of the codebase and rewriting them. Pre-optimisation is the problem here and it was a sign of my inexperience as a programmer.
I’ve since learned my lesson, and as I’ve stated previously Peripheral Labs has always been a way for me to learn new things and become better in general. So let’s get to the point.
What I was doing was trying to come up with the optimal way of doing things before writing any code at all. This was due to my logic of thinking, “if I get it perfect from the start, I wont have to go over it again and tweak it”. This is perfectly logical, however a flawed approach as I learned after scrapping my supposedly “perfect” code because it was over-engineered and didn’t really work that well.
The problem lie’s in the assumption that I can somehow optimise something that doesn’t exist. When I put it this way it seems ridiculous doesn’t it? Well it is, it’s just sometimes it’s hard for inexperienced programmers to realise things like this.
The way you should ideally write a piece of code goes something like this:
1. Write any old messy code WITHOUT classes or any other fancy feature. Just get it to work.
2. If it’s slow or inefficient, go over it and make it faster by optimising EXISTING code.
3. If you find yourself copy pasting code, then introduce structures and classes to clean up the code and make it more efficient to use the code base.
I find the above process works better, because firstly, I get something that works quicker (boosting moral on a project). And then optimising is easier and faster because I can actually see what the problem is, rather than trying to predict problems that might occur.
I also mentioned not using classes and structures at the start. I stand by this. As mentioned by many great programmers, one often find themselves stuck trying to design an object oriented system as they try and predict the needs for complex inheritance diagrams, when it’s often just not needed.
Anyway these are my thoughts on how to have a better time writing code. If you have your own opinion do share, I like people who challenge my opinions.