sergey-tihon / Clippit

Fresh PowerTools for OpenXml
https://sergey-tihon.github.io/Clippit/
MIT License
47 stars 18 forks source link

ManageMediaCopy: improvement ideas #54

Open f1nzer opened 2 years ago

f1nzer commented 2 years ago

After PR #53 method ManageMediaCopy uses Sha256 hash algorithm for duplicate media detection purposes.

But all media is zipped, so it's possible to use Crc32 checksum from every zip entry. This approach could remove unnecessary Sha calculation with an IO operation (read & hash) because Crc32 is already precomputed and available.

ZipArchiveEntry.Crc32 property was added in NetCore2.1, so it's important to use it carefully due to the current target framework (netstandard2.0)

Unfortunately, this property can't be easily accessed, so the only way is to use reflection.

Simple example how it could be used:

private uint GetCrc32(object srcObj)
{
    var packagePart = GetInternalProperty<ZipPackagePart>(srcObj, "PackagePart");
    var zipArchiveEntry = GetInternalProperty<ZipArchiveEntry>(packagePart, "ZipArchiveEntry");
    var crc32 = GetInternalProperty<uint>(zipArchiveEntry, "Crc32");
    return crc32;
}

srcObj might be ImagePart or DataPart.

Rough GetInternalProperty implementation:

private static T GetInternalProperty<T>(object srcObj, string propName)
{
    var prop = srcObj.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    return (T) prop!.GetValue(srcObj);
}

From my local tests it might improve performance by 15-20% on some large pptx file with many media elements 😄