From 8fc3e336ff845de0e84caaa9c6002fffbf109dc5 Mon Sep 17 00:00:00 2001 From: Kirill Shakirov Date: Mon, 27 May 2024 19:26:46 +0700 Subject: [PATCH] task: add slice on stack --- go/2024/other/optimize/s10.go | 2 +- go/2024/other/optimize/slice_on_stack.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 go/2024/other/optimize/slice_on_stack.go diff --git a/go/2024/other/optimize/s10.go b/go/2024/other/optimize/s10.go index 12d6b36..b491291 100644 --- a/go/2024/other/optimize/s10.go +++ b/go/2024/other/optimize/s10.go @@ -21,7 +21,7 @@ struct sorting fields preallocate map (or GC ballast) use ints instead of floats Boundary checks - Allocate the backing array of a slice on stack even if its size is larger than or equal to 64K (but not larger than 10M) +Allocate the backing array of a slice on stack even if its size is larger than or equal to 64K (but not larger than 10M) Avoid unnecessary pointer dereferences in a loop Use index tables instead of maps which key types have only a small set of possible */ diff --git a/go/2024/other/optimize/slice_on_stack.go b/go/2024/other/optimize/slice_on_stack.go new file mode 100644 index 0000000..feb209b --- /dev/null +++ b/go/2024/other/optimize/slice_on_stack.go @@ -0,0 +1,15 @@ +package main + +const N = 10 * 1024 * 1024 // 10M +var n = N / 2 + +func f() byte { + var a [N]byte // allocated on stack + for i := range a { + a[i] = byte(i) + } + var s = a[:] // a slice with 10M elements + + var p = &a + return s[n] + p[n] +}