Skip to content

Conversation

@kamilsk
Copy link
Owner

@kamilsk kamilsk commented Jan 3, 2021

a possible solution of the #158 issue

@kamilsk kamilsk added this to the retry 5.0 milestone Jan 3, 2021
@kamilsk kamilsk self-assigned this Jan 3, 2021
@kamilsk
Copy link
Owner Author

kamilsk commented Jan 3, 2021

package main

import (
	"context"
	"testing"
)

type Breaker interface {
	Done() <-chan struct{}
	Err() error
}

type breaker struct{}

func (*breaker) Done() <-chan struct{} { return nil }
func (*breaker) Err() error            { return nil }

func withCast(breaker Breaker) {
	ctx, is := breaker.(context.Context)
	if !is {
		ctx = context.Background()
	}
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
}

func withoutCast(breaker Breaker) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_, _ = breaker, ctx
}

func Benchmark(b *testing.B) {
	ctx := context.WithValue(context.Background(), "test", "test")

	b.Run("ctx, with cast", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			withCast(ctx)
		}
	})

	b.Run("ctx, without cast", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			withoutCast(ctx)
		}
	})

	br := new(breaker)

	b.Run("breaker, with cast", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			withCast(br)
		}
	})

	b.Run("breaker, without cast", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			withoutCast(br)
		}
	})
}
Benchmark
Benchmark/ctx,_with_cast
Benchmark/ctx,_with_cast-12         	 9668047	       111 ns/op	      80 B/op	       2 allocs/op
Benchmark/ctx,_without_cast
Benchmark/ctx,_without_cast-12      	12608467	        95.2 ns/op	      80 B/op	       2 allocs/op
Benchmark/breaker,_with_cast
Benchmark/breaker,_with_cast-12     	12399238	        96.5 ns/op	      80 B/op	       2 allocs/op
Benchmark/breaker,_without_cast
Benchmark/breaker,_without_cast-12  	13494591	        84.9 ns/op	      80 B/op	       2 allocs/op

@kamilsk kamilsk marked this pull request as ready for review January 3, 2021 11:14
@kamilsk kamilsk merged commit cd4b575 into v5 Jan 3, 2021
@kamilsk kamilsk deleted the issue-158 branch January 3, 2021 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant