Skip to content

Optimizing ReadLanguageWorkerFile to avoid LOH allocations by reading files in chunks #11069

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
- Fix invocation timeout when incoming request contains "x-ms-invocation-id" header (#10980)
- Warn if .azurefunctions folder does not exist (#10967)
- Memory allocation & CPU optimizations in `GrpcMessageExtensionUtilities.ConvertFromHttpMessageToExpando` (#11054)
- Memory allocation optimizations in `ReadLanguageWorkerFile` by reading files in buffered chunks, preventing LOH allocations (#11069)
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Script.Diagnostics;
using Microsoft.Azure.WebJobs.Script.Workers.Profiles;
using Microsoft.Extensions.Configuration;
Expand Down Expand Up @@ -357,13 +359,43 @@ internal bool ShouldAddWorkerConfig(string workerDescriptionLanguage)

private void ReadLanguageWorkerFile(string workerPath)
{
if (_environment.IsPlaceholderModeEnabled()
&& !string.IsNullOrEmpty(_workerRuntime)
&& File.Exists(workerPath))
if (!_environment.IsPlaceholderModeEnabled()
|| string.IsNullOrWhiteSpace(_workerRuntime)
|| !File.Exists(workerPath))
{
// Read language worker file to avoid disk reads during specialization. This is only to page-in bytes.
File.ReadAllBytes(workerPath);
return;
}

// Reads the file to warm up the operating system's file cache. Can run in the background.
_ = Task.Run(() =>
{
const int bufferSize = 4096;
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);

try
{
using var fs = new FileStream(
workerPath,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize,
FileOptions.SequentialScan);

while (fs.Read(buffer, 0, bufferSize) > 0)
{
// Do nothing. The goal is to read the file into the OS cache.
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error warming up worker file: {filePath}", workerPath);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
});
}
}
}