Skip to content

Commit 4e270d9

Browse files
authored
Don't hit all properties on Color in ColorTranslator (#106042)
KnownColor based Color values look up the value with every method/property access. Avoid this by making Color.GetRgbValues internal and use it in ColorTranslator. This is more of a hit in Windows where system colors also involve a system call. Fixes #105992
1 parent 47ebcf3 commit 4e270d9

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -483,7 +483,7 @@ public static Color FromName(string name)
483483
}
484484

485485
[MethodImpl(MethodImplOptions.AggressiveInlining)]
486-
private void GetRgbValues(out int r, out int g, out int b)
486+
internal void GetRgbValues(out int r, out int g, out int b)
487487
{
488488
uint value = (uint)Value;
489489
r = (int)(value & ARGBRedMask) >> ARGBRedShift;

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@ internal static uint COLORREFToARGB(uint value)
3232
/// </summary>
3333
public static int ToWin32(Color c)
3434
{
35-
return c.R << COLORREF_RedShift | c.G << COLORREF_GreenShift | c.B << COLORREF_BlueShift;
35+
// KnownColor Color values causes a table lookup or OS call for
36+
// every access, as such we manually extract the RGB values.
37+
38+
c.GetRgbValues(out int r, out int g, out int b);
39+
return r << COLORREF_RedShift | g << COLORREF_GreenShift | b << COLORREF_BlueShift;
3640
}
3741

3842
/// <summary>
@@ -386,7 +390,8 @@ public static string ToHtml(Color c)
386390
}
387391
else
388392
{
389-
colorString = $"#{c.R:X2}{c.G:X2}{c.B:X2}";
393+
c.GetRgbValues(out int r, out int g, out int b);
394+
colorString = $"#{r:X2}{g:X2}{b:X2}";
390395
}
391396

392397
return colorString;

0 commit comments

Comments
 (0)