github.com/moontrade/unsafe@v0.9.1/memory/mem_test.go (about)

     1  package memory
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  	"unsafe"
     7  )
     8  
     9  func TestCmp(t *testing.T) {
    10  	println(Cmp("hello", "hello0"))
    11  	println(Cmp("hello0", "hello"))
    12  	println(Cmp("hello", "hello"))
    13  }
    14  
    15  func BenchmarkCompare(b *testing.B) {
    16  	b.Run("Slow", func(b *testing.B) {
    17  		_a := "hello"
    18  		_b := "hello8"
    19  		__a := unsafe.Pointer(*(**uintptr)(unsafe.Pointer(&_a)))
    20  		__b := unsafe.Pointer(*(**uintptr)(unsafe.Pointer(&_b)))
    21  
    22  		for i := 0; i < b.N; i++ {
    23  			compareSlow(__a, __b, uintptr(len(_a)))
    24  		}
    25  	})
    26  	b.Run("Fast", func(b *testing.B) {
    27  		_a := "hello"
    28  		_b := "hello8"
    29  		__a := unsafe.Pointer(*(**uintptr)(unsafe.Pointer(&_a)))
    30  		__b := unsafe.Pointer(*(**uintptr)(unsafe.Pointer(&_b)))
    31  
    32  		for i := 0; i < b.N; i++ {
    33  			Compare(__a, __b, uintptr(len(_a)))
    34  		}
    35  	})
    36  }
    37  
    38  func compareSlow(a, b unsafe.Pointer, n uintptr) int {
    39  	if a == nil {
    40  		if b == nil {
    41  			return 0
    42  		}
    43  		return -1
    44  	}
    45  	ab := *(*string)(unsafe.Pointer(&reflect.SliceHeader{
    46  		Data: uintptr(a),
    47  		Len:  int(n),
    48  	}))
    49  	bb := *(*string)(unsafe.Pointer(&reflect.SliceHeader{
    50  		Data: uintptr(b),
    51  		Len:  int(n),
    52  	}))
    53  	if ab < bb {
    54  		return -1
    55  	}
    56  	if ab == bb {
    57  		return 0
    58  	}
    59  	return 1
    60  }
    61  
    62  func BenchmarkMemzero(b *testing.B) {
    63  	buf := make([]byte, 16)
    64  	buf[0] = 77
    65  	buf[15] = 88
    66  
    67  	Zero(unsafe.Pointer(&buf[0]), uintptr(len(buf)))
    68  
    69  	ptr := unsafe.Pointer(&buf[0])
    70  
    71  	b.Run("memclr", func(b *testing.B) {
    72  		for i := 0; i < b.N; i++ {
    73  			Zero(ptr, uintptr(len(buf)))
    74  		}
    75  	})
    76  
    77  	b.Run("slow", func(b *testing.B) {
    78  		for i := 0; i < b.N; i++ {
    79  			zeroSlow(ptr, uintptr(len(buf)))
    80  		}
    81  	})
    82  }