Skip to content
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

Fixing CA2014 warnings, and removing suppressions #17982

Merged
merged 4 commits into from Sep 13, 2022

Conversation

creative-cloud
Copy link
Contributor

@creative-cloud creative-cloud commented Aug 29, 2022

PR Summary

Fixes #13531 - No longer allocating memory in loops. Removed related suppress warnings.

Moved out the stackalloc statements for 2/3 cases, and removed the loop entirely for the other.

PR Context

Copying context over from the issue -

We currently suppress warnings of CA2014 in parts of the build. stackallocs in loops can cause stack overflows, so we need to refactor our code to fix this.

PR Checklist

@ghost
Copy link

ghost commented Aug 29, 2022

CLA assistant check
All CLA requirements met.

@creative-cloud creative-cloud requested review from iSazonov and removed request for daxian-dbw, anmenaga and adityapatwardhan August 30, 2022 05:15
@creative-cloud
Copy link
Contributor Author

Pinging the original reviewers, to get a few more eyes on the PR.
@anmenaga @adityapatwardhan @daxian-dbw

{
var endOfLine = Environment.NewLine.AsSpan();
var endOfLineLength = endOfLine.Length;
Span<char> outBufferLine = stackalloc char[outBuffer.Length + endOfLineLength];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we could allocate ~16KB (MaxBufferSize) in stack. That it is not good. I suggest to output the tail before the condition if the tail >= MaxStackAlloc ( MaxStackAlloc = 512).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@iSazonov
I think what you are suggesting is that we should further split the outBuffer into 2 pieces -> MaxBufferSize - 512b and 512b, such that the span that is stacalloc'ed is 512 bytes.
(assuming that the size of the outBuffer is MaxBufferSize, in the worst case)

The first MaxBufferSize - 512b piece will need additional memory. This will also end up going on the stack since we are using spans. This route does not seem any better than allocating the entire MaxBufferSize.

Also, this will mean that we would now need to make two WriteConsole calls to finish writing the contents of the outBuffer, rather than 1.
I don't think the memory allocation issue is significant enough to justify adding the perf of a whole other IO operation.

Let me know if I understood that right.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean:

        internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan<char> output, bool newLine)
        {
            Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
            Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");

            const char MaxStackAlloc = 512;
            Span<char> buffer = stackalloc char[MaxStackAlloc];
            ReadOnlySpan<char> outBuffer;

            // Native WriteConsole doesn't support output buffer longer than 64K.
            // We need to chop the output string if it is too long.
            // This records the chopping position in output string
            int cursor = 0;

            // this is 64K/4 - 1 to account for possible width of each character.
            const int MaxBufferSize = 16383;

            while (cursor <= output.Length - MaxBufferSize)
            {
                outBuffer = output.Slice(cursor, MaxBufferSize);
                cursor += MaxBufferSize;

                WriteConsole(consoleHandle, outBuffer);
            }

            if (cursor == output.Length)
            {
                if (newLine)
                {
                    WriteConsole(consoleHandle, Environment.NewLine);
                }

                return;
            }

            outBuffer = output.Slice(cursor);

            if (!newLine)
            {
                WriteConsole(consoleHandle, outBuffer);

                return;
            }

            if (outBuffer.Length < MaxStackAlloc - 1)
            {
                // We expect it is a hot path.
                var endOfLine = Environment.NewLine.AsSpan();
                var endOfLineLength = endOfLine.Length;
                buffer = buffer.Slice(0, outBuffer.Length + endOfLineLength);            }

                outBuffer.CopyTo(buffer);
                endOfLine.CopyTo(buffer.Slice(buffer.Length - endOfLineLength));

                WriteConsole(consoleHandle, buffer);
            }
            else
            {
                WriteConsole(consoleHandle, outBuffer);

                WriteConsole(consoleHandle, Environment.NewLine);
            }
        }

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Up.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@iSazonov I understand your concern here. But the while (cursor + MaxBufferSize < output.Length) comes from the existing if (cursor + MaxBufferSize < output.Length), so it's not a problem introduced by this cleanup change. So, I'm fine merging this PR as is, and submit a new PR to address your concern.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@daxian-dbw Agree.

@pull-request-quantifier-deprecated

This PR has 86 quantified lines of changes. In general, a change size of upto 200 lines is ideal for the best PR experience!


Quantification details

Label      : Small
Size       : +38 -48
Percentile : 34.4%

Total files changed: 3

Change summary by file extension:
.cs : +38 -48

Change counts above are quantified counts, based on the PullRequestQuantifier customizations.

Why proper sizing of changes matters

Optimal pull request sizes drive a better predictable PR flow as they strike a
balance between between PR complexity and PR review overhead. PRs within the
optimal size (typical small, or medium sized PRs) mean:

  • Fast and predictable releases to production:
    • Optimal size changes are more likely to be reviewed faster with fewer
      iterations.
    • Similarity in low PR complexity drives similar review times.
  • Review quality is likely higher as complexity is lower:
    • Bugs are more likely to be detected.
    • Code inconsistencies are more likely to be detected.
  • Knowledge sharing is improved within the participants:
    • Small portions can be assimilated better.
  • Better engineering practices are exercised:
    • Solving big problems by dividing them in well contained, smaller problems.
    • Exercising separation of concerns within the code changes.

What can I do to optimize my changes

  • Use the PullRequestQuantifier to quantify your PR accurately
    • Create a context profile for your repo using the context generator
    • Exclude files that are not necessary to be reviewed or do not increase the review complexity. Example: Autogenerated code, docs, project IDE setting files, binaries, etc. Check out the Excluded section from your prquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in your prquantifier.yaml context profile.
    • Only use the labels that matter to you, see context specification to customize your prquantifier.yaml context profile.
  • Change your engineering behaviors
    • For PRs that fall outside of the desired spectrum, review the details and check if:
      • Your PR could be split in smaller, self-contained PRs instead
      • Your PR only solves one particular issue. (For example, don't refactor and code new features in the same PR).

How to interpret the change counts in git diff output

  • One line was added: +1 -0
  • One line was deleted: +0 -1
  • One line was modified: +1 -1 (git diff doesn't know about modified, it will
    interpret that line like one addition plus one deletion)
  • Change percentiles: Change characteristics (addition, deletion, modification)
    of this PR in relation to all other PRs within the repository.


Was this comment helpful? 👍  :ok_hand:  :thumbsdown: (Email)
Customize PullRequestQuantifier for this repository.

Copy link
Member

@daxian-dbw daxian-dbw left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@daxian-dbw daxian-dbw assigned daxian-dbw and unassigned anmenaga Sep 12, 2022
@daxian-dbw daxian-dbw merged commit 2ec7aea into PowerShell:master Sep 13, 2022
@iSazonov
Copy link
Collaborator

@creative-cloud Thanks for your contribution!

@iSazonov iSazonov added the CL-General Indicates that a PR should be marked as a general cmdlet change in the Change Log label Sep 14, 2022
@TravisEz13 TravisEz13 mentioned this pull request Sep 30, 2022
22 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CL-General Indicates that a PR should be marked as a general cmdlet change in the Change Log Small
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Fix CA2014: Stackalloc in loops
4 participants