The pattern below is something I am seeing more and more in our code base.
Are there any performance concerns with using something like this on API responses that return large data sets?
export interface IPerson {
id: int,
name: string
}
export class Person implements IPerson{
id: int;
name: string;
constructor(person: any) {
this.id = person.id;
this.name = person.name;
}
}
// usage
let persons: IPerson[] = [];
this.httpClient.get().then(response => {
const _response = JSON.parse(response) as IPerson[];
_response.forEach(person => persons.push(new Person(person))
})
CodePudding user response:
There are no compilation performance issues with that code, which means that the only thing that needs to be considered is the JavaScript, which is
export class Person {
constructor(person) {
this.id = person.id;
this.name = person.name;
}
}
let persons = [];
this.httpClient.get().then(response => {
const _response = JSON.parse(response);
_response.forEach(person => persons.push(new Person(person))
})
Which is quite simple. The only way the above would be a problem would be if
- The Person constructor had expensive code inside it (such as nested loops) - which it doesn't
- Or, if you had an unreasonably large number of items in the response to begin with (like tens of thousands or more - halfway OK computers could handle quite a lot more) - but with that, the issue is more that the response is so huge to begin with, rather than the code here that does stuff with it.
For this code particularly, creating class instances for every object looks very strange. Classes are a decent approach when you want to tie methods to data together in a single object. If you have only data, using just plain objects and arrays usually makes more sense. That is, consider if you could change
_response.forEach(person => persons.push(new Person(person))
to
_response.forEach(({ id, name }) => persons.push({ id, name }))
It's also suspicious to be pushing to an outside array inside an asynchronous function, because that often leads some coders to attempt to use the array before it's been populated. Consider if having a Promise that resolves to the array of persons would suit your purposes instead.