Cost using class vs interface for memory and performance

Viewed 1624

When writing typescript for my angular application, I can create my domain objects with an Interface or a class. I am looking for hard data on the actual costs of using the class approach.

I know that using an interface does not generate any javascript code, but using a class does. Both approaches have the benefit of autocompletion and syntax checking.

I see more benefits of using classes - Easily unit tested - Business logic can be added to domain objects (which sounds good, when using Domain Driven Design) - We can force domain objects being immutable

So logically an interface is cheaper but I am trying to figure out if the costs of using a class actually outweigh the benefits.

For this I'd like to know what others' experience is in comparing the 2 approaches in a real application. Or if people know of performance tests that have been done in this area.

So far I've found this question (classes vs interfaces in Angular(TypeScript)) that suggests using an interface for my data models, but it doesn't give any hard data to be able to decide which approach would suit me best.

1 Answers

For super-simple data objects, use interfaces (or types). Examples: parameter objects, value types, and any other objects that don't require any built-in logic.

For anything more complicated, use classes. The overhead of this choice is minimal compared to the benefits you're getting, for example the ability to put some simple logic inside the class so you don't need to off-load it into a service. The class definition takes a little bit of memory, but in runtime, a class just means a specific prototype for the objects.

I admit this answer does not include any actual performance or statistics, but those would greatly depend on the type of object and context.

Also see this great comment on Github.

Related