Skip to content

Commit dc1318f

Browse files
QuocDatHoangDatHoang83twsouthwick
authored
Optimize ToFlatOpcString to reduce memory usage and improve performan… (#1863)
## Optimized the ToFlatOpcString method to address high memory usage and improve performance. The previous implementation relied on LINQ, which created a significant amount of intermediate collections and dictionaries, leading to inefficiency, especially when working with Word documents containing images. This update removes unnecessary LINQ operations and reduces memory overhead, replace manual chunking logic with Convert.ToBase64String using Base64FormattingOptions.InsertLineBreaks. This approach eliminates the need for LINQ-based chunking and aggregation, resulting in cleaner, more efficient code while adhering to the MIME specification for line breaks in Base64 encoding. A sample benchmark output when working with a 822KB-word document. ![image](https://github.com/user-attachments/assets/3efadb6b-9f0f-41d5-9e8d-9992d0296469) Co-authored-by: Dat Hoang Quoc <[email protected]> Co-authored-by: Taylor Southwick <[email protected]>
1 parent ed521b6 commit dc1318f

File tree

1 file changed

+1
-19
lines changed

1 file changed

+1
-19
lines changed

src/DocumentFormat.OpenXml.Framework/Packaging/FlatOpcExtensions.cs

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -141,25 +141,7 @@ private static string ToChunkedBase64String(IPackagePart part)
141141
}
142142

143143
private static string ToChunkedBase64String(byte[] byteArray)
144-
{
145-
// The MIME specification defines a maximum line length of 76 characters
146-
// for a Base64-encoded string. Therefore, we need to break down the
147-
// Base64 string into chunks of up to 76 characters each.
148-
const int maxLineLength = 76;
149-
150-
return Convert.ToBase64String(byteArray)
151-
.Select((@char, index) => new { Character = @char, Chunk = index / maxLineLength })
152-
.GroupBy(charAndChunk => charAndChunk.Chunk)
153-
.Aggregate(
154-
new StringBuilder(),
155-
(sb, grouping) => sb
156-
.Append(grouping.Aggregate(
157-
new StringBuilder(),
158-
(chunkSb, charAndChunk) => chunkSb.Append(charAndChunk.Character),
159-
chunkSb => chunkSb.ToString()))
160-
.Append(Environment.NewLine),
161-
sb => sb.ToString());
162-
}
144+
=> Convert.ToBase64String(byteArray, Base64FormattingOptions.InsertLineBreaks);
163145

164146
internal static IPackageFactory<TPackage> WithFlatOpcTemplate<TPackage>(this IPackageFactory<TPackage> builder, string text, bool? isEditable = default)
165147
where TPackage : OpenXmlPackage

0 commit comments

Comments
 (0)