I know that creating objects eats up memory and slows down the app ...
This generalization is problematic:
Yes, creating an object consumes memory and takes time, but it doesn't necessarily slow down the app. It depends on what the alternative to creating the object is. It could well be that the alternative slows down the app more.
And even assuming that the "create an object" version uses more resources than the alternative, there's a good chance that the difference won't be significant.
What you seem to be doing here is premature optimization. My advice is:
- let the JVM deal with the optimization (it can probably do it better than you anyway),
- leave any hand optimization to later, and only do it if the measured performance of the app actually warrants it, and
- use a CPU or memory profiler to guide you as to the parts of your code where going to the effort of hand optimizing is likely to have a good payoff.
As to the specifics of your use-case, it is not clear what the most efficient solution would be. It depends on things like how the strings are formed, how many branches there are in the switch statement, and things like that. It is hard to predict without profiling the application with realistic input data.
A third option that you didn't mention is to use an enum
instead of a String
or int
. That will be neater than implementing the String
to int
mapping using a pre-populated HashMap
or something.