Home > front end >  Golang for loop inside for loop string operation taking abnormal time
Golang for loop inside for loop string operation taking abnormal time

Time:12-20

Golang version : go version go1.13.5 windows/amd64

Please take a look at this code :

https://go.dev/play/p/pfqXLnuQfYA

When we run it on play then it is timing out.

In my local windows machine 16GB ram taking 50 seconds time. Another unix machine 96GB ram taking 1minute 8 seconds time.

Please give pointers what is going wrong in this? How come it is taking so much time ?

CodePudding user response:

As @icza pointed out, you're creating strings that are not used and get garbage collected, additionally using an old version of Go.

This program runs in 6.3s in my machine with go version go1.17.5 linux/amd64

func main() {
    startTime := time.Now()
    log.Println("for loop started")
    a := make([]string, 0)
    a = append(a, "N")
    x := 0
    for i := 0; i < 47831; i   {
        for j := 0; j < 47831; j   {
            a[0] = strings.ToLower(a[0])
            x  
        }
    }
    endTime := time.Now()
    log.Println("for loop end, time taken=", endTime.Sub(startTime), "iters=", x)
}

2021/12/20 10:26:22 for loop started
2021/12/20 10:26:29 for loop end, time taken= 6.323187151s iters= 2287804561

CodePudding user response:

As commented by @icza and answered by @Wolfgang, You can use latest version of Golang.

OR

If you want to make it fast then divide the task in different goroutines. It will definitely enhance the time.

These are the three factor due to which you are getting abnormal time.

At that time when the program started :

  1. Number of process in the waiting queue irrespective of the OS.
  2. CPU scheduling
  3. Clock speed of processor
  •  Tags:  
  • go
  • Related