Question

I have a Message class which parses text messages using lookup tables. I receive a lot of messages and create and destroy a lot of objects so I thought I declare those lookup tables as static members to prevent initializing the same tables with the same values again and again.

Is it the correct approach or there's more appropriate C++ way?

Thanks.

Was it helpful?

Solution

This sounds like the right way to do it, although I'd expect the compiler to optimize this. Have you benchmarked your application and does declaring the tables as static speed it up?

Also note that if you have many large lookup tables, performance will increase, but the tables will be hold in memory all the time.

OTHER TIPS

If your message classes share lookup information that it may be worth abstracting your static lookups into a class of their own so that they really are only initialised once.

But regardless, static class members are definitely the way to go.

They could be class variables, i.e. static at the class level. That way they are available to subclasses, if any, and perhaps a bit more visible than if "hidden" as static local variables in individual methods.

Yes, all ok. Sometimes it is good solution: function static which will created only once. Also you could use singleton object, but it has more wide accessibility.

Be careful if you have multi-threaded application and if your lookup-tables contain pointer to another data which could be destroyed early than this table.

Using a singleton pattern will also work for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top