Posts

Showing posts from August, 2024

Why should I initialise variables close to where they are used?

Image
You have all heard that you should initialise close to where you first use your variables instead of at the top of the class, since it's better to understand, less likely to break when modified, etc, but what other benefits will you get? We will look at the compiler to understand why you should care. But first we need to understand what your compiler is doing.  Escape Analysis in Compilers : Escape Analysis is an optimisation technique that allows your compiler to determine whether a variable is accessed, outside its scope. In other words: your compiler will check your variables and look for those which have only local access. If accesses are only local, then this is an opportunity for optimisation of the code via memory management. So what exactly is happening to these local variables? Stack Allocations : A variable found to be local, without accessing outside its scope, can be allocated on the stack instead of the heap. Fun fact : accessing data on the L1 cache takes 0.5 nanoseco...