Skip to content

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

Closed
@jackmott

Description

@jackmott

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions