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

SafePixelCollection.CheckIndex always allocates strings even if they aren't needed #1436

Closed
zlepper opened this issue Sep 19, 2023 · 4 comments
Milestone

Comments

@zlepper
Copy link

zlepper commented Sep 19, 2023

Magick.NET version

13.2.0 (Also relevant on main)

Environment (Operating system, version and so on)

Windows

Description

The code here: https://github.com/dlemstra/Magick.NET/blob/main/src/Magick.NET/Pixels/SafePixelCollection.cs#L196

    private void CheckIndex(int x, int y)
    {
        Throw.IfOutOfRange(nameof(x), 0, Image.Width - 1, x, $"Invalid X coordinate: {x}.");
        Throw.IfOutOfRange(nameof(y), 0, Image.Height - 1, y, $"Invalid Y coordinate: {y}.");
    }

Always allocates the 2 error strings, even if they aren't going to be used due to the interpolation.

Why is this an issue? Mainly because it causes extra work for the GC. If you want to get absolutely crazy, you can use create an interpolated string handler, that can conditionally create the string, as seen here: https://devblogs.microsoft.com/dotnet/string-interpolation-in-c-10-and-net-6/#debug-assert-without-the-overhead

Steps to Reproduce

Call GetPixel(x, y) with a memory profiler attached.

@dlemstra
Copy link
Owner

This not the only spot where this is happening and would require a lot of refactoring throughout the code. Using a lamba could probably resolve this issue.

Throw.IfOutOfRange(nameof(x), 0, Image.Width - 1, x, () => $"Invalid X coordinate: {x}.");

I don't know when I will have time to work on this. Feel free to open a pull request to change this. Maybe you could use UnsafePixelCollection for now because that class doesn't contain those checks.

@zlepper
Copy link
Author

zlepper commented Sep 22, 2023

I'm not sure a lambda would help as it still needs to capture the parameter, but I might take a look over the weekend to see if I can come up with something :)

@dlemstra
Copy link
Owner

Yup, I was also not sure about that. An other option would be to create different IfOutOfRange methods for these specific cases.

@dlemstra
Copy link
Owner

I was at a conference this week and went to a talk from @Elfocrash that gave me another idea. I will use string.Format for these methods instead.

@dlemstra dlemstra added this to the 13.4.0 milestone Oct 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants