Does using Random.new() for one time use cause memory leak

Heya, today I was just thinking about memory leaks and what could cause them, and for me, i quite use Random.new() alot, without setting a variable or something

for example i would get a random child like this

Folder:GetChildren()[Random.new():NextInteger(1, #Folder:GetChildren)

But I really never thought about the fact that creating a random everytime i want to get a random child could cause memory leaks? Im assuming it does make a memory leak because im creating a new random without ever destroying it.

Thanks in advance!

I will do some testing alright, interesting question

1 Like

Random.new() returns an object with methods, and it will be treated as an metatable object. That means its’ properties will not be garbage collected unless it’s properly cleaned up as a table. So when you call the constructor, it will exist in memory until it’s properly cleaned up using table.clear() and setmetatable(myRandomVariable, nil).

Essentially, you would prevent memory leaks if you define them and re-use them, rather than creating a new object each time. However, be aware that the constructor assigns a pseudorandom seed.

2 Likes



No memory usage. Only to store numbers.

Random:Destroy() also works no?

Dang you took my solution! Crazy

1 Like

My apologies for barging in, you don’t have to make my post the solution.

The Random object does not include a :Destroy method unfortunately, if you try to call the method in studio testing, it will error with an index nil.

2 Likes

I was just joking man, you had a good technical response.

2 Likes

You don’t actually need to manually clean it up. It’s just another normal userdatum that will garbage collect when it’s no longer referenced. Once it’s collected, the actual object it represents in the engine will be taken care of internally.

The only time userdata will cause memory leaks is if a strong reference is accidently kept, such as storing it in a table and not removing it or having a long-lasting closure keep an upvalue of it. If the only reference to it is in a local variable, you don’t have to worry about it.

3 Likes

That’s actually what I was just thinking about after making my post, because it wouldn’t make sense why the engineers haven’t already included a Destroy method into it / not being referenced anywhere. After thinking about the metatable metamethods for a little bit, I assumed it had a weak reference pre-defined with the constructor.

So I think your post is the actual solution, mine was more of a conjecture solely based on the documentation + theory.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.