0

I'm kind of new to classes and Object Oriented programming. I'm working on improving my skills, so I want to learn how they work.

Let's say I'm making a REST API with the following model:

// user.js
module.exports = {
  firstName: "",
  lastName: "",
  email: ""
}

Question 1: How would I convert something like this^ into a typescript class? And how would I call it in another file?


Let's say I've got this:

// user.js
class User { ... }

Question 2: When I execute an request on the API I get 20 SQL results back, would doing this:

// user-manager.js
import User from "./User";

users.forEach(user => {
  const userTemplate = new User( ... );
});

cause a memory leak, because I'm calling new 20 times? How does this work?

Please help me out here..

Thimma
  • 1,343
  • 7
  • 33
  • 1
    No, instantiating a class multiple times does not generally cause memory leaks. Why do you think it might? You're using `new` a lot in any halfway complex program, it would be a major flaw if that caused memory leaks. – deceze May 07 '20 at 07:32
  • I thought because it's new maybe it makes a `new` object every time? That's why I'm here, to get my question answered.. – Thimma May 07 '20 at 07:39
  • Yes, it *does* make a new object every time. What does that have to do with *memory leaks*? – deceze May 07 '20 at 07:40
  • Well, let's say I make a new object, that consumes some memory, right? So my thought process was: if i make a _new_ instance every-single-time that it will consume more memory over time, is that the case? – Thimma May 07 '20 at 07:42
  • 1
    You might want to revisit the definition of *memory leak*. No, you are creating 20 instances once, which allocates memory once, it will not consume more memory over time. Also, read about garbage collection! – Bergi May 07 '20 at 07:46
  • 1
    Yes, it will create a new instance every time and that will consume more memory every time, ***but*** values (including instances) go *out of scope* at some point (here: when your `forEach` callback function ends) and the allocated memory will be reclaimed by the garbage collector. That happens all the time with all values and is not unique to objects created with `new`. Otherwise yes, your program would eventually run out of memory. The definition of a *memory leak* is when that process doesn't behave correctly. – deceze May 07 '20 at 07:48
  • Yes, it allocates memory once for those 20 instances. But what if this script runs every second, so that means I get 20 `new` every second, that would consome a lot of memory right? – Thimma May 07 '20 at 07:48
  • @deceze Thanks! That was exactly what I needed - please post your comment as an aswer so I can give you some rep – Thimma May 07 '20 at 07:48

0 Answers0