diff --git a/doc/effective_go.html b/doc/effective_go.html
index 1743d0fa11..ddfea76d43 100644
--- a/doc/effective_go.html
+++ b/doc/effective_go.html
@@ -2106,12 +2106,14 @@ In this contrived example Sequence satisfies both.
The String method of Sequence is recreating the
-work that Sprint already does for slices. We can share the
-effort if we convert the Sequence to a plain
+work that Sprint already does for slices.
+(It also has complexity O(N²), which is poor.) We can share the
+effort (and also speed it up) if we convert the Sequence to a plain
[]int before calling Sprint.
func (s Sequence) String() string {
+ s = s.Copy()
sort.Sort(s)
return fmt.Sprint([]int(s))
}
@@ -2138,6 +2140,7 @@ type Sequence []int
// Method for printing - sorts the elements before printing
func (s Sequence) String() string {
+ s = s.Copy()
sort.IntSlice(s).Sort()
return fmt.Sprint([]int(s))
}
diff --git a/doc/progs/eff_sequence.go b/doc/progs/eff_sequence.go
index 11c885abf8..ab1826b6ee 100644
--- a/doc/progs/eff_sequence.go
+++ b/doc/progs/eff_sequence.go
@@ -28,11 +28,18 @@ func (s Sequence) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
+// Copy returns a copy of the Sequence.
+func (s Sequence) Copy() Sequence {
+ copy := make(Sequence, 0, len(s))
+ return append(copy, s...)
+}
+
// Method for printing - sorts the elements before printing.
func (s Sequence) String() string {
+ s = s.Copy() // Make a copy; don't overwrite argument.
sort.Sort(s)
str := "["
- for i, elem := range s {
+ for i, elem := range s { // Loop is O(N²); will fix that in next example.
if i > 0 {
str += " "
}