Skip to content

Commit

Permalink
Reduce allocation when reading PNG chunks
Browse files Browse the repository at this point in the history
Previously the code would read a byte[] for every PNG chunk, irrespective of whether it was going to be stored. With this change, these arrays are only allocated when they will actually be needed.

This is the .NET port of drewnoakes/metadata-extractor#535
  • Loading branch information
drewnoakes committed May 7, 2021
1 parent 7f52477 commit a131ad5
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions MetadataExtractor/Formats/Png/PngChunkReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
// Miscellaneous information: bKGD, hIST, pHYs, sPLT
// Time information: tIME
//
// CHUNK READING
//
// Only chunk data for types specified in desiredChunkTypes is extracted.
// For empty chunk type list NO data is copied from source stream.
// For null chunk type list ALL data is copied from source stream.
//

// network byte order
reader = reader.WithByteOrder(isMotorolaByteOrder: true);
Expand All @@ -68,7 +74,17 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
throw new PngProcessingException("PNG chunk length exceeds maximum");
var chunkType = new PngChunkType(reader.GetBytes(4));
var willStoreChunk = desiredChunkTypes == null || desiredChunkTypes.Contains(chunkType);
var chunkData = reader.GetBytes(chunkDataLength);

byte[]? chunkData;
if (willStoreChunk)
{
chunkData = reader.GetBytes(chunkDataLength);
}
else
{
chunkData = null;
reader.Skip(chunkDataLength);
}

// Skip the CRC bytes at the end of the chunk
// TODO consider verifying the CRC value to determine if we're processing bad data
Expand All @@ -85,7 +101,8 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
if (chunkType.Equals(PngChunkType.IEND))
seenImageTrailer = true;

if (willStoreChunk)
// chunkData will be null if we aren't interested in this chunk
if (chunkData is not null)
chunks.Add(new PngChunk(chunkType, chunkData));

seenChunkTypes.Add(chunkType);
Expand Down

0 comments on commit a131ad5

Please sign in to comment.