Ad

DTO Vs Hashmap: Maintainability Vs Memory Efficiency

- 1 answer

I'm having a debate on out DTOs. Whenever I need to return a subset or superset of the domain object's fields I create a new class with these fields use it in the code. Even if there is only single usecase for that.

Point 1 - eat more memory, write less code

This highly increases maintainability and readability, since my service method has only two lines of code. But if I used a hashmap, then there would be magic strings and no compile-time checking.

Point 2 - eat less memory, write more code

After returning the DTOto the client it's class metadata is still in the class loader. But if I used a hashmap, then I would not have this overhead. More impact if there are a lot of DTO classes.

What pragmatically has more impact?

Ad

Answer

You can't easily fill up the metaspace with classes, especially handwritten ones (as opposed to generated etc.). Of course you can constrain yourself so you have only minimal space available, but in a normal scenario it's not very likely.

So the effect of a class on the performance or memory use is completely irrelevant. The only reason you might want to avoid writing DTOs is because it requires programmer effort to write and maintain them. This can become problematic, but there are ways to deal with those too (such as the aforementioned generated classes).

So there's no (performance or memory) reason not to use DTOs, and there are plenty of reasons not to use Maps as you said. Type safety and code readability being the most obvious ones.

Ad
source: stackoverflow.com
Ad