A deep dive into benchmarking in Golang. We Measure the Power of Cars, Computers, and Cellphones. But What About Code?

I’m not going to lie — benchmarking is not one of my biggest strengths. I don’t do it nearly as often as I’d like. But it’s become more frequent since I started using Go as my primary language of choice. One of the reasons for this is because Go has some great built-in support for benchmarking.

Go lets us developers benchmark using the testing package. So the testing package comes with benchmarking powers included. That’s awesome!

In this article, I want to dive deeper into benchmarks, but I’ll start from scratch. After reading this, I hope I’ve provided you with a slightly better understanding of benchmarks.

Let’s start talking about benchmarking. Benchmarking in software development is about testing the performance of the code we write.

“A benchmark is the act of running a computer program, a set of programs, or other operations, in order to assess the relative performance of an object.”— Wikipedia

Benchmarking allows us to take different solutions and try their performance, comparing the measured speeds. This is great knowledge to possess as a developer, especially when you have an application you need to speed up and optimize.

It’s important to remember a golden rule in development: Never optimize prematurely. Just because we’ll learn how to benchmark doesn’t mean I suggest running and benchmarking every piece of code you have. I strongly feel that benchmarking is a tool to use when you face performance issues or when pure curiosity is killing you.

“Premature optimization is the root of all evil.”

— Donald E. Knuth, “The Art of Computer Programming”

It’s not uncommon to see posts on the internet from junior developers about different code solutions, asking which one is best. But saying something is the best when talking about code is something I prefer not to do.

Let’s stick to the expression most performant since sometimes slower code is more easily maintained and readable. Thus, that code is better, if you ask me, unless you’re faced with performance issues, of course.

Let’s begin learning how to benchmark using Go. I’ve gathered some questions from a junior developer that I couldn’t answer related to performance.

We’ll take a look at them for him.

  • Are slices or maps faster?
  • Is the speed of slices and maps affected by size?
  • Does the key type used within maps matter?

#programming #golang

A Deep Dive Into Benchmarking in Golang
1.90 GEEK