From 98a517c3e2f4e332cdcfc5564ca4b2e8ce8be9b3 Mon Sep 17 00:00:00 2001 From: Lam Luong Date: Mon, 6 Nov 2023 09:00:06 +0700 Subject: [PATCH] Reduce allocations during readNativeFrames with frame channel --- read.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/read.go b/read.go index 337735f9..e04846fa 100644 --- a/read.go +++ b/read.go @@ -256,9 +256,9 @@ func (r *reader) readPixelData(vl uint32, d *Dataset, fc chan<- *frame.Frame) (V if fc != nil { fc <- &f + } else { + image.Frames = append(image.Frames, &f) } - - image.Frames = append(image.Frames, &f) } image.IntentionallySkipped = r.opts.skipPixelData return &pixelDataValue{PixelDataInfo: image}, nil @@ -440,7 +440,13 @@ func (r *reader) readNativeFrames(parsedData *Dataset, fc chan<- *frame.Frame, v image.Frames = make([]*frame.Frame, nFrames) bo := r.rawReader.ByteOrder() pixelBuf := make([]byte, bytesAllocated) + nativeDataBuf := make([][]int, pixelsPerFrame) + buf := make([]int, pixelsPerFrame*samplesPerPixel) for frameIdx := 0; frameIdx < nFrames; frameIdx++ { + if fc == nil { + nativeDataBuf = make([][]int, pixelsPerFrame) + buf = make([]int, pixelsPerFrame*samplesPerPixel) + } // Init current frame currentFrame := frame.Frame{ Encapsulated: false, @@ -448,10 +454,9 @@ func (r *reader) readNativeFrames(parsedData *Dataset, fc chan<- *frame.Frame, v BitsPerSample: bitsAllocated, Rows: MustGetInts(rows.Value)[0], Cols: MustGetInts(cols.Value)[0], - Data: make([][]int, pixelsPerFrame), + Data: nativeDataBuf, }, } - buf := make([]int, pixelsPerFrame*samplesPerPixel) if bitsAllocated == 1 { if err := fillBufferSingleBitAllocated(buf, r.rawReader, bo); err != nil { return nil, bytesToRead, err @@ -482,9 +487,10 @@ func (r *reader) readNativeFrames(parsedData *Dataset, fc chan<- *frame.Frame, v currentFrame.NativeData.Data[pixel] = buf[pixel*samplesPerPixel : (pixel+1)*samplesPerPixel] } } - image.Frames[frameIdx] = ¤tFrame if fc != nil { fc <- ¤tFrame // write the current frame to the frame channel + } else { + image.Frames[frameIdx] = ¤tFrame } } if skipFinalPaddingByte {