FastIO in Go (For Competitive Coding)

To do comparision, we will note the time it takes to read 10^6 numbers from StdIn, store it into slice and then print all the numbers to StdOut.

Method - 1 (Naive Approach)

As a step to make myself stronger in Go, I started using it for competitive programming. I was using fmt package for IO, but soon I started getting timeout in IO heavy questions.

In this simple approach, we will use fmt.Scanf for reading, and we will not be using any buffered IO.

package main

import (
	"fmt"
)

func testIO() {
	arr := []int{}
	var n, t int 
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &t)
		arr = append(arr, t)
	}

	for _, val := range arr {
		fmt.Printf("%d ", val)
	}
}

func main() {
	testIO()
}

Time :
For N : 10**6
real 0m8.417s

Method - 2 (Buffered IO)

Now we will modify our code a little bit -

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func getInt(sc *bufio.Scanner) int {
	sc.Scan()
	out, _ := strconv.ParseInt(sc.Text(), 10, 0)
	return int(out)
}

func takeIO() {
	arr := []int{}

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	wt := bufio.NewWriter(os.Stdout)
	defer wt.Flush()

	n := getInt(sc)
	for i := 0; i < n; i++ {
		t := getInt(sc)
		arr = append(arr, int(t))
	}

	for _, val := range arr {
		fmt.Fprintf(wt, "%v\n", val)
	}
}

func main() {
	takeIO()
}

Time :
For N : 10**6
real 0m0.270s

Comparision

We gained a significant reduction in time, with minimal changes in our code.