user1894205
user1894205

Reputation: 137

Does using strongly typed classes result in more efficient Javascript?

I am working on porting a large .NET WinForms business application to Angular. I have a data model with a large number (~1500) of entities. In the .NET application each entity is modelled by a simple class, the vast majority of these classes have no methods beyond the properties exposing the fields of the entity. They are essentially used only for type safety.

Is it a good idea to reproduce this in a Javascript based application or (since I am using Typescript) should I just use interfaces to enforce compile time type safety? Given Javascript's more flexible approach to defining objects I could just add the properties i need at run time?

I am particularly interested in knowing whether the sheer bulk of the class definitions would be a performance hit, or rather if having the strongly typed classes would actually increase performance.

Upvotes: 0

Views: 396

Answers (1)

Sean Newell
Sean Newell

Reputation: 1113

tldr; I would just use interfaces to define the shape of data you need, since that is easier to use in JS code.

This SO answer points out that it is not a big difference until you instantiate a lot of object - I would say millions of objects per second.

Here's a good article on performance in Node, which will give you an idea of how it will be in Chrome (saying nothing about other browsers).

A bigger problem than performance efficiency, is developer efficiency. And I would argue that interfaces, as a more light-weight language construct, are easier to reason about than classes. In fact, it's easy to mixin an existing interface with another type, interface, or anonymous type like this:

interface Map {
  map: Function
}

interface Reduce {
  reduce: Function
}

type CustomType = Map & Reduce & { sum: Function }

const a: CustomType = {} // now you need to implement map, reduce, and sum

You just get so much reasoning power, without the class keyword, and 0 overhead. However, if classes meshes better with your team/codebase/use-case, go for it. You won't incur significant runtime overhead with just 1500 of them.

Upvotes: 2

Related Questions