I would start by building it with inlining disabled and assembler output enabled. Then compare the assembly code for main.A and main.B.
go build -gcflags 'all=-l -S' x.go 2>y On Tue, Mar 19, 2024 at 1:12 PM Mohamad Rostami <mb.rostam...@gmail.com> wrote: > Well, I used runtime runtime.MemStats StackInuse. > I don't have much knowledge about compiler optimization. > But to make it clear for myself: > > considering these 2 functions: > > //go:noinline > func A() { > var h int > for i := 0; i < 1e5; i++ { > h = i > _ = h > fmt.Printf("%+v\n", &h) > } > } > > //go:noinline > func B() { > for i := 0; i < 1e5; i++ { > h := i > _ = h > fmt.Printf("%+v\n", &h) > } > } > > The address of h in B is changing in each iteration although it's not > causing stack to grow. > > If you point me to the documentation for this specific case, I would > appreciate it. > Regards, > > On Tuesday, March 19, 2024 at 5:46:36 PM UTC+1 Ian Lance Taylor wrote: > >> On Tue, Mar 19, 2024 at 9:36 AM Mohamad Rostami <mb.ros...@gmail.com> >> wrote: >> > >> > I've seen in many places in go source code re-declaring a variable with >> the same name. >> > e.g: >> > for i < j { >> > h := ... >> > } >> > Instead of >> > var h int >> > for i < j { >> > h = ... >> > } >> > >> > So I did a benchmark to check the differences. I didn't find any >> performance related differences, but in terms of Stack Memory in use, the >> second approach is better than the first one. >> > >> > Not sure if the way is in standard library is by intention or something >> that should be ignored. >> >> The two versions are basically equivalent. How are you measuring >> stack memory usage? If they are different, there may be something to >> fix in the compiler. >> >> Ian >> > -- > 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. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/3818a025-d46c-4e23-8b2e-6e0a08c0986an%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/3818a025-d46c-4e23-8b2e-6e0a08c0986an%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- Kurtis Rader Caretaker of the exceptional canines Junior and Hank -- 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. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CABx2%3DD_e_yiTmQyFeznmk%2BYAzocrAq3UjPgpVxMh9czTQ0PwHA%40mail.gmail.com.