From c9255b11f77504995c0426412910a0d0588cca7f Mon Sep 17 00:00:00 2001 From: Marc-Antoine Ruel Date: Tue, 8 May 2018 13:21:02 -0400 Subject: [PATCH] apa102: remove allocation in Halt Document where Draw() cause a memory allocation in the case of an image format other than NRGBA. --- devices/apa102/apa102.go | 13 +++++++++++-- devices/apa102/apa102_test.go | 8 ++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/devices/apa102/apa102.go b/devices/apa102/apa102.go index f1167f2..a372e08 100644 --- a/devices/apa102/apa102.go +++ b/devices/apa102/apa102.go @@ -124,8 +124,16 @@ func (d *Dev) Write(pixels []byte) (int, error) { // Halt turns off all the lights. func (d *Dev) Halt() error { - _, err := d.Write(make([]byte, d.numPixels*3)) - return err + // Zap out the buffer. + for i := range d.pixels { + if i&3 == 0 { + // 0xE0 would probably be fine too. + d.pixels[i] = 0xE1 + } else { + d.pixels[i] = 0 + } + } + return d.s.Tx(d.rawBuf, nil) } // @@ -293,6 +301,7 @@ func (l *lut) rasterImg(dst []byte, r image.Rectangle, src image.Image, srcR ima } else { // Generic version. for sX := srcR.Min.X; sX < srcR.Max.X; sX++ { + // This causes a memory allocation. There's no way around it. r16, g16, b16, _ := src.At(sX, srcR.Min.Y).RGBA() r := l.r[byte(r16>>8)] g := l.g[byte(g16>>8)] diff --git a/devices/apa102/apa102_test.go b/devices/apa102/apa102_test.go index 0f08bb7..6798a9e 100644 --- a/devices/apa102/apa102_test.go +++ b/devices/apa102/apa102_test.go @@ -674,6 +674,14 @@ func BenchmarkWriteColorfulVariation(b *testing.B) { } } +func BenchmarkHalt(b *testing.B) { + d, _ := New(spitest.NewRecordRaw(ioutil.Discard), 150, 250, 5000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + d.Halt() + } +} + // type configFail struct {