Sorry, just thought it could also use clear to start getting accostumed :)

<code>
// GroupValue returns a new Value for a list of Attrs. 
// The caller must not subsequently mutate the argument slice. 
func GroupValue(as ...Attr) Value { 
    // Remove empty groups.
    // It is simpler overall to do this at construction than
    // to check each Group recursively for emptiness.
    var write int
    for read := range as {
        if !as[read].isEmptyGroup() {
            if read != write {
                as[write] = as[read]
            }
            write++
        }
    }
    clear(as[write:]) // no need to keep a reference to the string Key
    as = as[:write]
    return Value{num: uint64(len(as)), any: groupptr(unsage.SliceData(as))}
}
</code>
On Monday, 14 August 2023 at 22:06:57 UTC-3 Diego Augusto Molina wrote:

> Hello everyone, thank you for reading. I'm looking at the code of 
> slog.GroupValue (
> https://cs.opensource.google/go/go/+/refs/tags/go1.21.0:src/log/slog/value.go;l=171)
>  
> and was wondering if we could benefit from reusing the same slice like this:
>
> <code>
> // GroupValue returns a new Value for a list of Attrs. 
> // The caller must not subsequently mutate the argument slice. 
> func GroupValue(as ...Attr) Value { 
>     // Remove empty groups.
>     // It is simpler overall to do this at construction than
>     // to check each Group recursively for emptiness.
>     var write int
>     for read := range as {
>         if as[read].isEmptyGroup() {
>             as[read] = Attr{} // no need to keep a reference to the 
> string Key
>         } else {
>             if read != write {
>                 as[write] = as[read]
>             }
>             write++
>         }
>     }
>     as = as[:write]
>     return Value{num: uint64(len(as)), any: groupptr(unsage.SliceData(as))}
> }
> </code>
>
> This, considering that the documentation of the func already states that 
> the user must not mutate the argument slice, so not only the elements but 
> the whole slice could be reused.
> In the case of having lots of attributes with empty group elements, then 
> the stored slice will be unnecessarily larger by that number of Attr 
> elements, but I wonder if that would be negligible, probably an edge case 
> of misuse.
>
> Kind regards.
>

-- 
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/71b83821-b6e2-4ed0-9d36-a97ed1dba290n%40googlegroups.com.

Reply via email to