I have many objects using few classes (means elements visual categorization like in html+css). Classes are not known at compile-time and they are used in conditions many times.
To improve performance I’ve got one solution:
public class ElementClass {
private static final Map<String, ElementClass> classes = new HashMap<>();
public final String name;
public final String lowerName;
public ElementClass(String name, String lowerName) {
this.name = name;
this.lowerName = lowerName;
}
public static ElementClass get(String name) {
String lower = name.toLowerCase();
ElementClass c = classes.get(lower);
if (c == null) {
c = new ElementClass(name, lower);
classes.put(lower, c);
}
return c;
}
}
The method get is used very less than comparison of ElementClass variables. It is in parsing configurations and for some static variables. I’m not sure if this is the best way to go, because I’m Java beginner.
The examples usage of ElementClass:
// contains element styles based on it's class
Map<ElementClass,ElementStyle> styles;
void exampleFunction() {
ElementClass c = ElementClass.get("special");
for( Element e : elements ) {
if( e.cls == c ) doSomethingSpecial();
}
}
This would be a textbook implementation of a cache. If there aren’t many ElementClasses and if your program is single-threaded, this will be enough.
I don’t see the need to keep the lowercase name inside the
ElementClass. It is enough to use it as the map key. I also assume there’s more to theElementClassin your project since now it just contains a name.Update
After clarification it became obvious that you do indeed only intend to use the
String name. In such a case it would be much better to make eachElementjust contain its lowercase name, but interned:Then you can compare
element.name == "special"and be guaranteed to match any names that are equal to "special".