Skip to content
loading...

re: How do you decide what order to put code in? VIEW POST

FULL DISCUSSION
 

In the context of C and C++, at least, the distance between functions can be significant to performance.

If function A calls function B frequently, the two should be listed near each other in the code. That way, when things are compiled, the actual assembly instructions for function A and function B will be near each other (unless optimized otherwise by the complier toolchain).

That distance between functions is important for minimizing the effects of instruction cache misses, as a function call is a literal GOTO instruction (unless it's been inlined). The same is often true of member variables, by the way.

At least, that's what I'd always been taught, and my work in C++ seems to confirm it.

At the same time, I almost always group functions by their scope, putting public above protected and private in most cases. If I have no other factors at play, I'll also organize alphabetically. However, if one function makes heavy use of another, I'll try to shuffle things around to move them closer together. In especially performance-critical areas, I am not opposed to "breaking up" my scope groups to accomplish this.

But, again, if there's no such scenarios you need to worry about, go for practical and pretty - group by scope, organize alphabetically, constructors first, destructors last (within their scope).

code of conduct - report abuse