Skip to content

Commit 89498d8

Browse files
authored
Improve RGB Min Max evaluation performance by using 2 or 3 comparison… (#50622)
1 parent 12edbc0 commit 89498d8

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -487,12 +487,34 @@ private void GetRgbValues(out int r, out int g, out int b)
487487
b = (int)(value & ARGBBlueMask) >> ARGBBlueShift;
488488
}
489489

490+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
491+
private static void MinMaxRgb(out int min, out int max, int r, int g, int b)
492+
{
493+
if (r > g)
494+
{
495+
max = r;
496+
min = g;
497+
}
498+
else
499+
{
500+
max = g;
501+
min = r;
502+
}
503+
if (b > max)
504+
{
505+
max = b;
506+
}
507+
else if (b < min)
508+
{
509+
min = b;
510+
}
511+
}
512+
490513
public float GetBrightness()
491514
{
492515
GetRgbValues(out int r, out int g, out int b);
493516

494-
int min = Math.Min(Math.Min(r, g), b);
495-
int max = Math.Max(Math.Max(r, g), b);
517+
MinMaxRgb(out int min, out int max, r, g, b);
496518

497519
return (max + min) / (byte.MaxValue * 2f);
498520
}
@@ -504,8 +526,7 @@ public float GetHue()
504526
if (r == g && g == b)
505527
return 0f;
506528

507-
int min = Math.Min(Math.Min(r, g), b);
508-
int max = Math.Max(Math.Max(r, g), b);
529+
MinMaxRgb(out int min, out int max, r, g, b);
509530

510531
float delta = max - min;
511532
float hue;
@@ -531,8 +552,7 @@ public float GetSaturation()
531552
if (r == g && g == b)
532553
return 0f;
533554

534-
int min = Math.Min(Math.Min(r, g), b);
535-
int max = Math.Max(Math.Max(r, g), b);
555+
MinMaxRgb(out int min, out int max, r, g, b);
536556

537557
int div = max + min;
538558
if (div > byte.MaxValue)

src/libraries/System.Drawing.Primitives/tests/ColorTests.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,12 @@ private void CheckRed(Color color)
390390
[InlineData(51, 255, 51, 0.6f)]
391391
[InlineData(51, 51, 255, 0.6f)]
392392
[InlineData(51, 51, 51, 0.2f)]
393+
[InlineData(0, 51, 255, 0.5f)]
394+
[InlineData(51, 255, 0, 0.5f)]
395+
[InlineData(0, 255, 51, 0.5f)]
396+
[InlineData(255, 0, 51, 0.5f)]
397+
[InlineData(51, 0, 255, 0.5f)]
398+
[InlineData(255, 51, 0, 0.5f)]
393399
public void GetBrightness(int r, int g, int b, float expected)
394400
{
395401
Assert.Equal(expected, Color.FromArgb(r, g, b).GetBrightness());

0 commit comments

Comments
 (0)