Right now I have an array of std::strings, and have a function in my font to find how wide it is.
for(std::vector<std::pair<std::string,bool>>::const_iterator it = items.begin();
it != items.end(); ++it)
{
cSz = getFont().getTextWidth(it->first);
if( cSz > h)
{
h = cSz;
}
}
widestItem = h;
I was wondering if I was possibly overlooking a better way to do this since this is a very brute-force way to find it.
In my situation there wouldn’t be much point in storing the width of each one and referring to that.
Thanks
If I were optimizing this I’d:
Make sure to use a profiler to find out that this is where significant time is going.
Maybe have a cache of (font, string) tuples. If you’re repeatedly computing the width of the same strings, this will help. But it depends on your exact use case.
You can make your getTextWidth method very fast in the common case – you can have a flat array of 256 text-width units, and just dereference and sum up for each latin-1 character you’ve got. That’ll be fast enough that you won’t see the time spent on a modern CPU. Of course, you still have to implement non-Latin characters, and you may or may not want to do kerning, ligatures, and complex text layout (which is where this stuff can get expensive).