array of buttons with text; how to avoid loading the font multiple times

I made a class for a button with text. the setup function for this button looks like:

void textButton::setupTextButton(int x,int y, string text, string font, int fontSize){  
     akkurat.loadFont(font, fontSize);  
    textButtonsRect=akkurat.getStringBoundingBox(text, x, y);  

This is working fine however when I want to create large arrays of those text buttons it’s very slow. I guess it’s because the font is loaded multiple times even if it’s the same font.

This is probably more a c++ questions. How could I optimize? so when I initialize a new text button if the font was already loaded it won’t load it again.

Thank you for your help

hi paul, yeah that’s your problem.

load the text only once in the testapp::setup() ,or in your class constructor, or use a bool named smthng like (loadfonts) that will be turned false after loading your fonts .

all load functions should be called only once

hi kkkkkkkk
thanks for your reply. how do you pass the already loaded font from testApp to inside the button class? does it has to do with pointer?
could you show me an example?

yes you can pass it by using a pointer,

or you can just declare a new TTF string in your textButton class…

Anyways. if you want to pass it via a pointer it’s very easy, there are two ways to do it.

by using pointer * and & reference operators

or by using two pointers *

so here is an “example”

in your testapp.h you declare a pointer

ofTrueTypeFont * font  

and in your textButton.h you do the same:

ofTrueTypeFont * fontPntr  

then, in your testApp::setup()

you dynamically allocate the new TTF font

by using new operator

font = new ofTrueTypeFont;  

then load your stuff but instead of using the . operator you should use the ->

then in your textButton.h & textButton:: setupTextButton

you modify your

//void setupTextButton(int x,int y, string text, string font, int fontSize);  
//to become:  
void setupTextButton(int x,int y, string text, ofTrueTypeFont * _TTF);  

do the same in your .cpp

then you do

fontPntr = _TTF;  

YOU DO NOT CALL THE NEW OPERATOR IN HERE you just point a pointer to another pointer.

(it will not lag but again it’s a “mistake” to do pointer = pointer inside a loop)

your pass pointer function should be called in the constructor of your
textButton class…

Hi kkkkkkkk
Thanks a lot for your help, it worked and increased the performances a lot!
Also was very useful exemple to understand the interest of using pointers.