Skip to content

proposal: spec: allow cap(make([]T, m, n)) > n #24204

Open

Description

@mdempsky

Currently, the Go spec requires that cap(make([]T, n)) == n and cap(make([]T, m, n)) == n. I propose relaxing this constraint from == to >=.

Rationale: the Go runtime already pads allocations up to the next malloc bucket size. By treating the user supplied capacity argument as a lower bound rather than exact bound, there's a possibility to make use of this padding space.

Also, if users really need an exact capacity (which seems like it would be very rare), they can write make([]T, n)[:n:n] or make([]T, m, n)[:m:n].

(See also discussion in #24163.)

Activity

  1. added
    v2An incompatible library change
    on Mar 1, 2018
  2. added this to the Proposal milestone on Mar 1, 2018
  3. bradfitz commented on Mar 1, 2018

    @bradfitz
    Contributor

    It would be hard to "gofix" this in some hypothetical "go1to2" tool. We'd need to conservatively rewrite all make into make([]T, m, n][:m:n] which would make the rewritten code pretty ugly.

  4. josharian commented on Mar 1, 2018

    @josharian
    Contributor

    It might be an interesting experiment to hack this into the compiler/runtime and do a regression test and see what breaks (@dsnet).

    Yes, it'd be ugly, but the gofix rule would at least be very simple.

    As I noted in #24163, this optimization could be made opt-in (instead of opt-out) with an appropriate runtime function.

    There's another option in this arena, which is to say "roughly" rather than == or >= in the spec, as we do with maps. The compiler and runtime could use this freedom along with PGO or introspection to make better decisions, treating the info from the user as just a hint to be used when no other info was available.

  5. cznic commented on Mar 1, 2018

    @cznic
    Contributor

    The three-index syntax of a slice was introduced to extend the precise control of slice cap. The proposal, even though in a different place, goes exactly the opposite way. I realize it can bring some performance improvements, but that's IMO not a good reason for breaking backward compatibility with Go 1 programs. Please consider a new syntax enabling this feature. There are plenty of options.

  6. bradfitz commented on Mar 1, 2018

    @bradfitz
    Contributor

    Please consider a new syntax enabling this feature. There are plenty of options.

    make([]T, 2, ~10)

    Fortunately the bitwise complement operator is ^, freeing up tilde!

  7. cznic commented on Mar 1, 2018

    @cznic
    Contributor

    make([]T, 2, 10+)

  8. josharian commented on Mar 1, 2018

    @josharian
    Contributor

    Also time.NewTicker(~3*time.Second). (I’m mostly joking, but macOS actually does support vague timers; they can be coalesced for power savings or spread to avoid cpu spikes.)

  9. mdempsky commented on Mar 1, 2018

    @mdempsky
    ContributorAuthor

    As I noted in #24163, this optimization could be made opt-in (instead of opt-out) with an appropriate runtime function.

    That becomes rather clumsy though, because to properly round you'll need to incorporate the element size too, not just the element count. So users would have to write something like:

    make([]T, runtime.RoundUp(n * unsafe.Sizeof(T{})) / unsafe.Sizeof(T{}))
    

    or

    make([]T, runtime.RoundUp(n, unsafe.Sizeof(T{})))
    

    (And of course T{} needs to be changed appropriately if T is something other than an array/struct/slice/map type.)

    The three-index syntax of a slice was introduced to extend the precise control of slice cap.

    That control is important, but seems exceedingly rarely used.

    Looking through Google's internal Go code base, I've found only a couple uses of full slice expressions, and they're all of the form:

    x = append(x[:len(x):len(x)], y)
    

    where the original x slice came from somewhere else (e.g., function argument or global), and they want to make sure to create a new slice.

    I strongly suspect the majority of users don't care about how much capacity is allocated for them by make. I don't see any evidence that users are dissatisfied with the lack of control over exactly how much
    capacity is allocated by append when it needs to grow the slice, for example. If they were, I'd expect to see full slice operations used in other contexts.

  10. faiface commented on Mar 1, 2018

    @faiface

    (Don't get offended.) This proposal basically proposes to cripple the language and make it less predictable (like really, imagine debugging a bug caused by this) in order to accommodate a very minor CPU-architecture-specific performance optimization. This mistake has been done many times in many languages. Don't make Go one of them.

  11. slrz commented on Mar 1, 2018

    @slrz

    I have recently written some code that would be broken by this change. Easy to fix, of course, but it'd be interesting to know whether this is more common.

    The gist of it was:

    var commonPrefix = make([]byte, N)
    
    func f(arg Type) []byte {
            return append(commonPrefix, computeSuffix(arg)...)
    }
    
  12. mdempsky commented on Mar 1, 2018

    @mdempsky
    ContributorAuthor

    This proposal basically proposes to cripple the language

    I think that's strongly overstating the potential downsides.

    Here's a simple experiment to just uniformly overallocate every make call of less than 1000 elements:

    --- a/src/runtime/slice.go
    +++ b/src/runtime/slice.go
    @@ -58,6 +58,10 @@ func makeslice(et *_type, len, cap int) slice {
                    panic(errorString("makeslice: cap out of range"))
            }
     
    +       if uintptr(cap) < 1000 && et.size < 10000 {
    +               cap++
    +       }
    +
            p := mallocgc(et.size*uintptr(cap), et, true)
            return slice{p, len, cap}
     }
    

    This breaks a couple standard library and regress tests, but they all appear to be for verifying that make itself works according to spec.

    There was one hairy crash in runtime/trace, which I've now diagnosed. The process for tracking it down was:

    1. I first searched for appearances of "cap(" in runtime/trace/*.go; finding none, I looked in runtime/*.go.
    2. I noticed "allp[:cap(allp)]" in runtime/trace.go, so then I looked at where allp was allocated.
    3. In proc.go, we allocate make([]*p, nprocs).
    4. I experimentally changed this to make([]*p, nprocs)[:nprocs:nprocs], and the crash went away.

    I would argue the real issue here is that runtime is using an inconsistent mix of len(allp) and cap(allp). Another fix that works perfectly fine is just changing all cap(allp) to len(allp), which seems desirable if only to keep the code simpler and easier to understand.

    (like really, imagine debugging a bug caused by this)

    It didn't seem too bad. :)

  13. josharian commented on Mar 2, 2018

    @josharian
    Contributor

    Here's a simple experiment

    Now that you have it working, if you change it to round up instead, are there any notable stdlib benchmark changes?

    Interestingly, allp cap issues were also what I hit with CLs 21813 and 22197, which changed append behavior, which is further evidence that just using len is probably better in this case.

  14. 26 remaining items

  15. seebs commented on Aug 8, 2021

    @seebs
    Contributor

    I ran into this recently, in the context of knowing a size I wanted to request, but it would definitely be preferable to actually use the whole space (just building buffers, so no benefit to me in a subslice of a buffer followed by unused space).

    I'd been thinking about how to express this, and in something more like C, I'd probably advocate for make([]byte, n, -1) for "enough to hold n bytes, but whatever you have is fine". I don't think that would break existing code, but it feels pretty messy. I also thought of _ for a don't-care value, but again, that feels messy.

  16. seebs commented on Sep 26, 2021

    @seebs
    Contributor

    And here I am running into exactly this again, having totally forgotten about it since the last time was... apparently a bit over a month ago.

    I spent a little time noodling on concepts like, say, runtime.SizeRounded(...), but anything using that looks a lot messier; you end up having to handle size-per-item yourself, and so on, or you pass in an object and runtime is using reflect, or it's a compiler special case... and at that point, we already have make/append being compiler-magic, and doing the right thing.

    One alternative that would require a bit of work, but would be more unambiguously new, would be to use a 4-argument make, so (type, len, cap, extra), but it's not obvious that "extra" could have anything meaningful -- really, the only practical cases are (1) i want an exact cap, (2) i want a cap rounded up to size class. if i want more than one size class of rounding, i should probably just specify a larger goal anyway.

    So really, I think that of the things that I've seen, make([]foo, l, c...) is probably the clearest; it allows expressing that i definitely want a cap of at least c, which may be larger than l, but that i don't actually need it to be no-more-than, and would prefer the size class rounding if that applies.

  17. dsnet commented on Sep 26, 2021

    @dsnet
    Member

    With #45955 we have:

    // Grow grows the slice's capacity, if necessary, to guarantee space for
    // another n elements. After Grow(n), at least n elements can be appended
    // to the slice without another allocation. If n is negative or too large to
    // allocate the memory, Grow will panic.
    func Grow[S constraints.Slice[T], T any](s S, n int) S

    which I assume has the freedom to allocate a larger capacity than len(s)+n, and also presumably one that lands on a size class boundary.

    Would this suffice for what this issue is aiming to accomplish?

  18. Jorropo commented on Apr 3, 2022

    @Jorropo
    Member

    Problem

    FYI, this is a real issue for me, I am implementing a opt slice optimization pass. And It's made more complex and less effective because of the strict definition of cap(make([]T, l, c)) == c.

    What I write fuses slice operations together.
    For example it turns:

    a = append(append(a, b...), c...)

    Into:

    a = slices.Grow(a, len(b)+len(c))
    a = a[:len(a)+len(b)+len(c)]
    copy(a[len(a):], b)
    copy(a[len(a)+len(b):], c)

    Which is faster, do only one allocation and is smaller.

    Doing that with slices from make is not pratical, it requires extensive escape analysis and proving that the shared part of the slice is not overwritten (which does not even work in all cases we would want to).
    Simply, with the current spec this behaviour is observed:

    a := make([]int, 10)
    b := append(a, 1) // b MUST be a copy of a, because the required capacity is 10+1 and a's capacity is 10.
    doStuff(a)
    fmt.Println(b[0]) // 0 even if doStuff do a[0] = 1

    That forbid to write the optimization that we want here:

    a := make([]int, 10, 11)
    b := a[:10] // Take a reference instead
    b[10] = 1
    doStuff(a) // a[0] = 1
    fmt.Println(b[0]) // it is now 1 modified by doStuff (wrong)

    Solutions

    On the solutions sides of things, this is a breaking change of the spec, however I have never seen code that relies on that.
    To me it seems everyone use new := append(a[:0:0], a...) or new := make([]typ, len(a)); copy(new, a) when you want a copy of a slice.
    So maybe, this would be fine to break ? On the other hand, having what used to be copies now be references sounds like a very insidious and really hard to find bug, and that isn't easily statically searchable either because the make and the append can be separated by 3 package boundaries and 2 interface ones and this property still hold (altho in this condition the optimizer would likely not be able to optimize this anyway).

    I do like @bcmills's solution (#24204 (comment)).
    But I don't know if it's worth having teach to new go developers that there is two 2 make, a slower builtin one, and a potentially faster slice.Make one, their syntax isn't even matching and the one you probably want is the longer to write, so I don't know if we expect should expect new go devs to use it much.

  19. Jorropo commented on Apr 3, 2022

    @Jorropo
    Member

    @dsnet
    Grow isn't really what this issue is asking for.
    If you use it that way it's equivalent:

    s := slices.Grow([]Type(nil), c)[:l]

    But that is very unergonomic.

    slices.Grow would be a more less direct equivalent to C++'s vector.reserve call.
    In day to day programing you would use it like this:

    // assume data is a slice of whatever type
    data = slices.Grow(data, len(more))
    for _, v := range more {
      data = append(data, process(v))
    }
  20. CAFxX commented on Apr 26, 2022

    @CAFxX
    Contributor

    Was thinking about this again and there may be a way (that AFAICT has not been proposed yet) to get the same benefits without language changes: modifying append to check if there is any unused tail in the current allocation, past the slice capacity.

    Let's say the user has initially allocate the slice with make([]byte, 0, n). The slice capacity is n, but the actual allocation is rounded up to the next sizeclass. When the user asks to append to the slice, and the append can't be satisfied with the current capacity n, growslice would then check if by extending the slice capacity to cover the sizeclass of the allocation the append could be satisfied without malloc+move: if so, it extends the capacity of the slice to the sizeclass size and performs just the copy from the source slice.

    This would AFAIK preserve all current semantics (I am not aware of any guarantees made by append on the capacity after an append) while allowing to use the whole allocation if possible, would not require users to know specific incantations, and would have the potential benefit of reducing the amount of unused space in allocation tails (because slice capacities would tend to end up sizeclass-aligned after repeated appends). The biggest problem would be figuring out how to know whether the allocation tail is really unused, or if the user has manually shrunk the capacity (and therefore the tail can't really be used) but it doesn't seem like an impossible problem.

  21. randall77 commented on Apr 26, 2022

    @randall77
    Contributor

    @CAFxX I don't think we can quite do that, unfortunately, due to the problem you mention at the end.

    s := make([]byte, n, n)
    s[n-1] = 77
    t := s[:n-1:n-1]
    

    When we append to t, can we overwrite the 77? I don't think we can. Depending on n, I don't see how to distinguish the cases of originally allocating the full size class and 3-arg slicing it down (in which case we can't use the
    tail space), versus allocating less than the full size class initially (in which case we can).

    We could figure that out by recording the actual allocated size in the heap metadata somehow. But that brings up the additional problem of multiple threads are simultaneously appending to t. How do we coordinate who gets to use that tail space? We'd need some atomic access guarding who gets to use the tail space.

    It may be doable, but doesn't seem easy (coding-wise), and possibly seems expensive (runtime-wise).

  22. CAFxX commented on Apr 26, 2022

    @CAFxX
    Contributor

    Yes, the simplest (but untested and somewhat still incomplete) idea I could come up with so far is storing a small (AFAIK we really need a single bit to signal whether the tail can be used or not) flag in the tail (or head) of the allocation, and accessing it atomically during modifications to the slice capacity (that, assuming uncontended access, shouldn't be horribly slow).

    Definitely, it wouldn't be trivial... but OTOH it would have pretty important upsides (works transparently for existing code, no language additions/redefinitions, no special syntaxes to get the compiler to do the right thing, ...)

  23. thepudds commented on May 19, 2022

    @thepudds
    Member

    Following up on the comment from @dsnet from last fall, one update is that Grow in x/exp/slices does now take advantage of the optimization @josharian described above so that the capacity gets rounded up to the next alloc size class:

    func Grow[S ~[]E, E any](s S, n int) S {
    	return append(s, make(S, n)...)[:len(s)]
    }
    

    A similar optimization might be possible in the Copy function there. (I will look at that and possibly send a CL if it makes sense).

    And of course, people could have their own generic Make that follows a similar pattern.

  24. mateusz834 commented on Jan 2, 2024

    @mateusz834
    Member

    Have you considered making this kind of change with the use of go directive (similarly to loop variable semantics)?

  25. changed the title [-]proposal: Go 2: allow cap(make([]T, m, n)) > n[/-] [+]proposal: spec: allow cap(make([]T, m, n)) > n[/+] on Aug 6, 2024
  26. added
    LanguageChangeReviewDiscussed by language change review committee
    and removed
    v2An incompatible library change
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Aug 6, 2024
  27. ianlancetaylor commented on Aug 14, 2024

    @ianlancetaylor
    Contributor

    @mateusz834 The loop variable semantics change was a one-off, done because we felt it was important enough to break our own rules. We aren't going to do it again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions