Simple tips to write efficient code

Simple tips to write efficient code

No alt text provided for this image

Programming CPU heavy data processing and analysis tasks? Some of my clients are amazed by the execution speed of my code, and I am not a professional software developer! Nevertheless, here are some of my simple tricks to keep in mind when writing code in any language:

  • Do calculations only once: avoid repeating the same arithmetic, try to store results in memory and reuse them later (yes more management!)
  • Watch loops contents… if it contains repetitive inefficient code, this code is triggered many times!
  • Example of inefficient code inside a loop: if/else and switch statements to process user options. Process options outside the loop and write several variants of the loop!
  • Avoid writing a ton of 1- or 2-lines functions just to make things “cute”. Call stack can become heavy and slow in the computer
  • Use the built-in language features, for example the vectorized operations in R, Matlab or Python, or the native functions in VBA and JavaScript (they will always be faster than your own implementation)
  • With object-oriented languages: write classes! Code is always cleaner and simpler to debug.
  • Having a code profiler? Profile execution and work on most time-consuming steps.

Again, these are just some of the things I keep in mind when I code something… But it helps a lot!


To view or add a comment, sign in

More articles by Vincent Béchard, MASc.

Explore content categories