Append consecutive slices, same underlying array

96 views
Skip to first unread message

Nick Patavalis

unread,
Oct 20, 2016, 9:11:14 AM10/20/16
to golang-nuts
Hi,

It seems that the built-in append does not check for a situation like
the following, and needlessly copies data, when it could avoid it.

  func appendBytes(a, b []byte) []byte {
          if len(b) == 0 {
                  return a
          }
	  // Shouldn't append() check for something like this?
          if cap(a) >= len(a)+len(b) && &a[:len(a)+1][len(a)] == &b[0] {
                  return a[:len(a)+len(b)]
          }
          return append(a, b...)
  }

If I'm following the breadcrumbs correctly, they lead to the fact that
runtime-memmove() does *not* short-circuit when source and destination
addresses are the same (I may be wrong, though).

Running the benchmark at:

  https://gist.github.com/npat-efault/f055654633f43d0ef771d38657fd499e

for any value of N, demonstrates this.

Rather marginal (and possibly very contrived) case, but I though I'd
point it out...

/npat

T L

unread,
Oct 20, 2016, 10:22:27 AM10/20/16
to golang-nuts, np...@efault.net
yes, you are right. You can file an issue at https://github.com/golang/go/issues

Nick Patavalis

unread,
Oct 20, 2016, 6:25:44 PM10/20/16
to golang-nuts, np...@efault.net
Reply all
Reply to author
Forward
0 new messages