Go runtime is dominated by the costs of allocation and GC.

If you return 10000 persons, then if we make the (unrealistic) assumption 
that a Person contains not pointers (strings etc). then returning []Person 
would require one allocation, whereas returning []*Person would require 
10,001. And GC will be much slower as there will be 10,000 more objects to 
mark.
Iteration across the returned slice will also be much faster in the former 
case, as each Person will 
reside in (cache friendly) sequential memory locations, whereas in the 
latter case the memory location
of each person will be effectively randomised and entail a cache miss.

So in general returning []Person will be much faster. 
Of course you should make sure you pre-allocate the entire slice, rather 
than letting it grow automatically
as the result of appends.


On Friday, 4 February 2022 at 09:43:28 UTC pauloaf...@gmail.com wrote:

> I appreciate your help.
>
> Em sexta-feira, 4 de fevereiro de 2022 às 00:12:47 UTC-3, 
> ren...@ix.netcom.com escreveu:
>
>> I think the OPs question was specifically about the cost of returning 
>> from a function - it is the same. 
>>
>> > On Feb 3, 2022, at 8:03 PM, Connor Kuehl <cipk...@gmail.com> wrote: 
>> > 
>> > On Thu, Feb 3, 2022 at 7:07 PM Paulo Júnior <pauloaf...@gmail.com> 
>> wrote: 
>> >> 
>> >> Hi all. 
>> >> 
>> >> I hope you are well. 
>> >> 
>> >> Is there a big difference, in terms of performance or functionality, 
>> between declaring []*Person or []Person as a return type of a function? 
>> > 
>> > If you find yourself iterating over a group of structs like this a lot 
>> > (especially if there's a lot of them to iterate over), you might want 
>> > to consider measuring the performance differences between []*Person or 
>> > []Person. With pointers, the actual structs might be far away from 
>> > each other in memory, which may prevent you from taking full advantage 
>> > of your processor's cache since it won't be able to benefit from the 
>> > spatial locality that an array (or slice) offers. 
>> > 
>> > Connor 
>> > 
>> > -- 
>> > 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...@googlegroups.com. 
>> > To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/golang-nuts/CAC_QXZS-QEKTgvsK3TKk-yUyc1jP81HngHz6dcDV8bZwqLBT6Q%40mail.gmail.com.
>>  
>>
>>
>

-- 
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/1f76f2e2-a26a-4f05-bb5a-435f98a93219n%40googlegroups.com.

Reply via email to