Created
June 6, 2019 09:57
-
-
Save rosspatil/bb0a2182e3e9ccfc4e124a3eddb600e3 to your computer and use it in GitHub Desktop.
This program provide simple hack to optimised slice return. When you return slice it will escape to heap but this program contains simple hack to avoid slice escape to heap.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"unsafe" | |
) | |
func main() { | |
heapOptimised() | |
normal() | |
} | |
func heapOptimised() string { | |
ba := returnBytes() | |
ptr := unsafe.Pointer(&ba) | |
return *(*string)(ptr) | |
} | |
func normal() string { | |
ba := returnBytes() | |
return string(ba) | |
} | |
func returnBytes() []byte { | |
str := "roshan" | |
ptr := unsafe.Pointer(&str) | |
return *(*[]byte)(ptr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Benchmark without use of return value
Benchmark_normal-4 200000000 7.17 ns/op 0 B/op 0 alloc/op
Benchmark_heapOptimised-4 2000000000 0.72 ns/op 0 B/op 0 alloc/op
Benchmark when allocating return value in global variable
Benchmark_heapOptimised-4 30000000 36.0 ns/op 16 B/op 1 alloc/op
Benchmark_normal-4 20000000 56.9 ns/op 24 B/op 2 alloc/op