Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Reducing relocations with Q_STRINGTABLE


enum Type { NoType, TypeA, TypeB, TypeC, _NumTypes };
const char * const type2string[] = { "", "A", "B", "C", };
static_assert(sizeof type2string / sizeof *type2string == _NumTypes);

const char __string_A[2] = "A"; // ok, no relocation
const char __string_B[2] = "B"; // ditto
const char __string_C[2] = "C"; // ditto
const char * const type2string[4] = {
    // oops, 4 entries each requiring relocation:
    &__string_A[1], // optimisation: common suffix is shared
    &__string_A[0],
    &__string_B[0],
    &__string_C[0],
};

static const struct {
    QRgb color;
    const char * name;
} colorMap[] = {
    { qRgb(0xFF, 0xFF, 0xFF), "white" },
    { qRgb(0xFF, 0x00, 0x00), "red"   },
    { qRgb(0x00, 0xFF, 0x00), "green" },
    // ...
};

const char type2string[2][] = { "", "A", "B", "C", }; // ok, type2string is an array of const char[2], no relocs
static const struct {
    QRgb color;
    const char name[6]; // ok, name is const char[6]
} colorMap[] = {
    // same as before
};

    static const QRgb colors[] = { qRgb(0xFF, 0xFF, 0xFF), ... };
    static const char names[6][] = { "white", ... };

static const QRgb colors[] = { qRgb(0xFF, 0xFF, 0xFF), qRgb(0xFF, 0x00, 0x00), ... };
static const char names[] = { "white\0" "red\0" ... };
static const uint nameOffsets[] = { 0, 6, 10, ... };
// the i-th name is names[nameOffsets[i]]

#define COLORS \
    (("white", qRgb(0xFF, 0xFF, 0xFF))) \
    (("red",   qRgb(0xFF, 0x00, 0x00))) \
    ...
    /*end*/
Q_STRINGTABLE_DATA_UNSORTED(ColorMap, COLORS)
#undef COLORS

if (const QRgb *color = ColorMap::find("red"))
    // found
else
    // not found

1 Comment

27 - Jun - 2015

Jaweriya