I’m writing a Java servlet that acts as a Front Controller. To carry out functions I’m using the Domain Command pattern. Currently, I’m initializing all my commands and storing them in a map with the name (string) of the command as the key and the object as the value. Whenever the servlet receives a request, I get the command from the map by passing the command query from url as:
// at init
Hashmap<String, DomainCommand> commands = new Hashmap<String, DomainCommand>();
commands.put("someCommand", new SomeCommand());
// at request
String command = request.getParameter("command");
DomainCommand c = commands.get(command);
c.execute();
This works well and does what I want since my DomainCommands have no class attributes to be shared between threads. An alternative to this is using reflection to create the object like so:
String command = request.getParameter("command");
DomainCommand c = Class.forName(command).newInstance(); // assuming in same (default) package
c.execute();
Both of these work. Which is better from a performance/memory saving point of view?
Performance
When using
Mapthe only cost is accessing aHashMap(negligible). Reflection on the other hand might take much more time and is less safe – remember you have to make sure the user is not passing boguscommand, allowing him to run arbitrary code.Memory
When creating
DomainCommandat startup they will end up in old generation after some time, thus not being subject to garbage collection for most of the time. On the other when created per request most likely they will be garbage collected immediately. So in overall, the memory footprint will be comparable, except that the second approach requires mor GC runs.All in all, map of commands is a much better approach. BTW if you DI frameworks like Spring or Guice (unless this is an overkill for you) or web frameworks like Struts/Spring MVC, they will do precisely the same work for you.