Optimize QColor::setNamedColor

This patch removes two memory allocations from the algorithm.

Change-Id: I9366f9c5ce02fb1cae8adfbd8dff36c7f23af2a7
Reviewed-by: Marc Mutz <marc.mutz@kdab.com>
This commit is contained in:
Jędrzej Nowacki 2014-03-28 15:29:05 +01:00 committed by The Qt Project
parent a3ed9b781c
commit ef2a2a9c03
2 changed files with 15 additions and 7 deletions

View File

@ -301,9 +301,8 @@ inline bool operator<(const RGBData &data, const char *name)
static bool get_named_rgb(const char *name_no_space, QRgb *rgb) static bool get_named_rgb(const char *name_no_space, QRgb *rgb)
{ {
QByteArray name = QByteArray(name_no_space).toLower(); const RGBData *r = std::lower_bound(rgbTbl, rgbTbl + rgbTblSize, name_no_space);
const RGBData *r = std::lower_bound(rgbTbl, rgbTbl + rgbTblSize, name.constData()); if ((r != rgbTbl + rgbTblSize) && !(name_no_space < *r)) {
if ((r != rgbTbl + rgbTblSize) && !(name.constData() < *r)) {
*rgb = r->value; *rgb = r->value;
return true; return true;
} }
@ -319,7 +318,7 @@ bool qt_get_named_rgb(const char *name, QRgb* rgb)
int pos = 0; int pos = 0;
for(int i = 0; i < len; i++) { for(int i = 0; i < len; i++) {
if(name[i] != '\t' && name[i] != ' ') if(name[i] != '\t' && name[i] != ' ')
name_no_space[pos++] = name[i]; name_no_space[pos++] = QChar::toLower(name[i]);
} }
name_no_space[pos] = 0; name_no_space[pos] = 0;
@ -334,7 +333,7 @@ bool qt_get_named_rgb(const QChar *name, int len, QRgb *rgb)
int pos = 0; int pos = 0;
for(int i = 0; i < len; i++) { for(int i = 0; i < len; i++) {
if(name[i] != QLatin1Char('\t') && name[i] != QLatin1Char(' ')) if(name[i] != QLatin1Char('\t') && name[i] != QLatin1Char(' '))
name_no_space[pos++] = name[i].toLatin1(); name_no_space[pos++] = name[i].toLower().toLatin1();
} }
name_no_space[pos] = 0; name_no_space[pos] = 0;
return get_named_rgb(name_no_space, rgb); return get_named_rgb(name_no_space, rgb);

View File

@ -530,10 +530,19 @@ static const int rgbTblSize = sizeof(rgbTbl) / sizeof(RGBData);
void tst_QColor::setNamedColor() void tst_QColor::setNamedColor()
{ {
for (int i = 0; i < rgbTblSize; ++i) { for (int i = 0; i < rgbTblSize; ++i) {
QColor color;
color.setNamedColor(QLatin1String(rgbTbl[i].name));
QColor expected; QColor expected;
expected.setRgba(rgbTbl[i].value); expected.setRgba(rgbTbl[i].value);
QColor color;
color.setNamedColor(QLatin1String(rgbTbl[i].name));
QCOMPARE(color, expected);
// name should be case insensitive
color.setNamedColor(QString(rgbTbl[i].name).toUpper());
QCOMPARE(color, expected);
// spaces should be ignored
color.setNamedColor(QString(rgbTbl[i].name).insert(1, ' '));
QCOMPARE(color, expected); QCOMPARE(color, expected);
} }
} }