std.posix.getenv: early-return comparison #23265
Open
+15
−7
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Addresses the issue described in #22917.
Possibly interferes with @andrewrk work on https://github.com/ziglang/zig/tree/main branch.
Original implementation https://github.com/ziglang/zig/blob/aa3db7cc15/lib/std/posix.zig#L2004 for each environment variable iterates until the end of its name (until
=
), and only then compares entire name tokey
.Since some of the environment variables could be quite long (i.e.
GHOSTTY_SHELL_INTEGRATION_NO_SUDO=1
), these sizes add up.Simply - in order to find a
key
inenviron
, it has to iterate over cumulative sizes of each env variable name before it.Proposed implementation functionally does what
strncmp
would do: stops iterating and moves to the next variable on first character mismatch withkey
.See the benchmarks below.
Disclaimer: this was tested on macOS, with a variation of #23264 fix applied.
To address the elephant in the room: this loop is duplicated, but I'm hesitant to refactor it in order to deduplicate because of
// TODO see https://github.com/ziglang/zig/issues/4524
preamble and ongoing work to fix it.