Skip to content

range based for loop slower than standard for loop on array #16907

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jackmott opened this issue Aug 28, 2016 · 2 comments
Closed

range based for loop slower than standard for loop on array #16907

jackmott opened this issue Aug 28, 2016 · 2 comments

Comments

@jackmott
Copy link

Please answer these questions before submitting your issue. Thanks!

  1. What version of Go are you using (go version)?

1.7 windows/amg64

  1. What operating system and processor architecture are you using (go env)?

set GOARCH=amd64
set GOBIN=
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=c:\projects\clarity\go
set GORACE=
set GOROOT=C:\Go
set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64
set CC=gcc
set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0
set CXX=g++
set CGO_ENABLED=1

  1. What did you do?

Compared the runtime of a standard for loop vs a range for loop with the following code:

package main

import "fmt"
import "time"

func main() {
    var values [32000000]float64
    for i := 0; i < len(values); i++ {
        values[i] = 2.0
    }

    for j := 0; j < 10; j++ {
        start := time.Now().UnixNano()
        sum := 0.0
        for i := 0; i < len(values); i++ {
            v := values[i]
            sum = sum +  v*v
        }
        end := time.Now().UnixNano()

        fmt.Printf("forloop sum %f time: %d\n",sum, (end-start)/1000000)

        start = time.Now().UnixNano()
        sum = 0.0
        for _,v := range values {
            sum = sum +  v*v
        }
        end = time.Now().UnixNano()

        fmt.Printf("range sum %f time: %d\n",sum, (end-start)/1000000)
    }
}
  1. What did you expect to see?

I am told runtime should be identical, or nearly so

  1. What did you see instead?

Runtime starts out ~4 times slower for the range loop on the first pass, then ~2x slower thereafer.

@davecheney
Copy link
Contributor

Please write a proper testing.Benchmark benchmark. What you are likely benchmarking is your processors L2/L3 cache.

@jackmott
Copy link
Author

Thank you, a testing.Benchmark test did reveal the runtime to be the same, and in my benchmark reversing the order of the tests also swapped the runtime. I'll close this.

@golang golang locked and limited conversation to collaborators Aug 28, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants