I think I failed to come up with a good code example. But suppose I need to
do something with a pointer inside a loop that really does require
dereferencing it and the pointer never changes inside the loop. In that
case will the Go compiler optimize that so the dereference doesn't happen
in each loop iteration?

On Fri, Nov 30, 2018 at 11:36 AM Jan Mercl <0xj...@gmail.com> wrote:

>
> On Fri, Nov 30, 2018 at 6:16 PM Mark Volkmann <r.mark.volkm...@gmail.com>
> wrote:
>
> > Will the Go compiler optimize the pointer dereference so it doesn't
> happen in every loop iteration? If not, is it common practice to do that
> outside the loop like this?
> >
> > myValue := *myPtr
> > for _, v := range values {
> >         fmt.Printf("%v %v\n", myValue, v)
> > }
>
> There's no pointer dereference inside the loop. But there's an allocation
> inside the loop, on every iteration, that puts a pointer to a copy of
> myValue into an interface{} that's passed to fmt.Printf. The allocation can
> be probably avoided:
>
> myValue := interface{}(*myPtr)
> for _, v := range values {
>         fmt.Printf("%v %v\n", myValue, v)
> }
>
> But the %v verb handle pointers in many cases well. If that holds for the
> type of *myPtr then simply:
>
> for _, v := range values {
>         fmt.Printf("%v %v\n", myPtr, v)
> }
>
> is what could be good enough.
>
> --
>
> -j
>


-- 
R. Mark Volkmann
Object Computing, Inc.

-- 
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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to