Aha, maybe the benchmark has flaw.
Here is another version:

package main

import (
    "testing"
)

const N = 1024 * 1024 // number of elements
type Element int64
var x = make([]Element, N)
var y []Element


func Benchmark_CloneWithAppend(b *testing.B) {
    for i := 0; i < b.N; i++ {
        y = append([]Element(nil), x...)
    }
}

func Benchmark_CloneWithCopy1(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        t := make([]Element, N)
        copy(t, x)
        y = t
    }
}

func Benchmark_CloneWithCopy2(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        copy(y, x)
    }
}

/*
$ go test -bench=.
Benchmark_CloneWithAppend-4           2000        732057 ns/op
Benchmark_CloneWithCopy1-4            1000       1816773 ns/op
Benchmark_CloneWithCopy2-4            3000        528175 ns/op
*/

So now the question becomes "why CloneWithCopy1 is so inefficient than 
CloneWithCopy2?".

On Tuesday, June 27, 2017 at 10:58:28 PM UTC+8, T L wrote:
>
>
> package main
>
> import (
>     "testing"
> )
>
> const N = 1024 * 1024 // number of elements
> type Element int64
> var x = make([]Element, N)
> var y []Element
>
>
> func Benchmark_CloneWithAppend(b *testing.B) {
>     for i := 0; i < b.N; i++ {
>         y = append([]Element(nil), x...)
>     }
> }
>
> func Benchmark_CloneWithCopy(b *testing.B) {
>     b.ResetTimer()
>     for i := 0; i < b.N; i++ {
>         t := make([]Element, N)
>         copy(t, x)
>         y = t
>     }
> }
>
> /*
> $ go test -bench=.
> Benchmark_CloneWithAppend-4           2000        738281 ns/op
> Benchmark_CloneWithCopy-4             1000       1822462 ns/op
> */
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to