r/learnprogramming • u/just_jesse • Jul 12 '13
What are some bad coding habits you would recommend a beginner avoid getting into?
Whether they're stylistic habits or program design habits. I'm learning java and want to be sure to write my code as efficiently as possible to avoid lengthy code and poor design choices.
245
Upvotes
View all comments
Show parent comment
4
u/[deleted] Jul 12 '13 edited Jul 13 '13
Note: this post is about what microoptimization is. As far as why it's bad, it's usually a huge waste of time.
Here are a few examples that can be fairly relevant in C:
First: Data Structure Alignment.
Second: Not jumping is better than jumping, so if you know that an if statement is really unlikely to actually evaluate to true, performance gains can be found by doing shit like:
This works for a few reasons, first, the code can still be run in the context of your current function and wont require anything like saving registers (thats why you use a GOTO), second, instead of a false evaluation causing you to jump over a block of code, a true evaluation will jump to a block of code. These days you can use likely and unlikely (gcc macros) to do this. NOTE: YOU SHOULD NEVER DO THIS UNLESS YOU HAVE A VERY GOOD REASON. IT'S DUMB AND YOUR PROCESSOR LIKELY HAS VERY GOOD BRANCH PREDICTION.
Most of the places I've seen shit like this are inside the Linux kernel where the performance gains are actually worth it in the end, and in general you shouldn't worry about these things unless you're writing something truly performance critical.
One thing you SHOULD care about, however (and this is usually true in non-c languages as well), is milti-dimensional array access. If you have an array like this:
Accessing it like this is very bad:
In C (and likely other languages behind the scenes) your outer array is a contiguous block of pointers to other memory. So someArray[20] is an int * which points to the first address of a block of memory exactly large enough to hold 1024 ints; and someArray[21] points to a different, likely adjacent, block of memory that is large enough to hold 1024 different ints image version.
When you access the array as mentioned in the example, outside of just being somewhat unintuitive, you're going to thrash [utilize poorly] your CPU cache. It will load all the memory at someArray[20], then access one value, then throw it all away, then load all the memory at someArray[21] access one value, throw it away, etc. Just don't do it, ever. The performance loss can be an order of magnitude or more.