The scope of this article is just to illustrate the performance of arrays using the go language while iterating on different sizes of them, compared with accessing data directly (the same amount of items but not using an array).

The interesting thing is that:

1. Accessing memory on small arrays(100 items) is slower than accessing memory on a single var in a for loop of the same size,
2. Accessing memory on bigger arrays (10.000 items) is faster than accessing memory on a single var in a for loop of the same size,
3. Accessing memory on more bigger arrays (100.000 items) is faster than accessing memory on a single var in a for loop of the same size.

Let's start illustrating the code that i'm using as the base example. This program is very simple, it prints out the times table of the numbers that you pass to it.

I've created two constants to pass the dimension of the arrays:

• `NUM` i.e. the multiplicand
• `MULTIPLIERS` i.e. the multipliers

If i set the NUM and the MULTIPLIERS constants to the value of 10 (100 items) i get:

``````Execution with array took 268.772µs
Execution without array took 180.132µs
``````

If i set the NUM and the MULTIPLIERS constants to the value of 100 (10.000 items) i get:

``````Execution with array took 133.748902ms
Execution without array took 145.693206ms
``````

If i set the NUM to the value of 1000 and the MULTIPLIERS to the value of 100 (100.000 items) i get:

``````Execution with array took 11.424318589s
Execution without array took 11.463020857s
``````

Here is the code:

``````package main

import (
"fmt"
"time"
)

func main() {

// Define our parameters here.
// Change the values to see how performance change
const NUM int = 10
const MULTIPLIERS int = 10

arrayStart := time.Now()
fmt.Println(arrayTimesTable(NUM, MULTIPLIERS))
elapsedArray := time.Since(arrayStart)
//fmt.Printf("Execution took %s\n", elapsedArray)

fmt.Println("--------------------------------------------------------------------------")

start := time.Now()
fmt.Println(timesTable(NUM, MULTIPLIERS))
elapsed := time.Since(start)

fmt.Printf("Execution with array took %s\n", elapsedArray)
fmt.Printf("Execution without array took %s\n", elapsed)
}

func arrayTimesTable(num, multipliers int) string {
m := ""
N := num
M := multipliers

arr := make([]int, N)
for i := range arr {
arr[i] = i + 1
}

timesTable := make([]int, M)
for k := range timesTable {
timesTable[k] = k + 1
}

for i := 0; i < len(arr); i++ {
for t := 0; t < len(timesTable); t++ {
res := [...]int{arr[i] * timesTable[t]}
m += fmt.Sprintf("%v * %v: %v\n", i + 1, t + 1, res)
}
}
return m
}

func timesTable(num int, multipliers int) string {
m := ""
for i := 0; i <= num; i++ {
for t := 0; t <= multipliers; t++ {
res := i * t
m += fmt.Sprintf("%d * %d: %d\n", i, t, res)
}
}
return m
}
``````

You'll only receive email when they publish something new.