What is the most efficient way to initialize an instance?

Initializing - Setting properties to stuff

So for instance, I have this section of code in a script, which is setting up a TextLabel, parenting it to a BillboardGui in the Instance.new() as a parameter, then setting up each property as usual.

Is there any better way to initialize an Instance? Particularly more efficient ones.

This should already be efficient, but to make it more efficient, its recommended that you do not use the 2nd argument in Instance.new() due to performance.

1 Like

Why not just place it in StarterGui and make it invisible, then move it over when you need to?

Oh that’s interesting. How come? I thought the extra line would cost perf slightly…

Oh true lol, thanks for thinking of that. Bit late now, although that would be an ideal solution

This is normally what I end up doing when I need to instance things in. However, I normally find just having everything there pre-run, and making it visible when needed works most of the time.

There is a post from 2016 explaining why, and how.

1 Like

Ah, thanks to both of you

I would like your posts but I’m at the like limit… :frowning:

3 Likes

What I usually do is create a the UI asset and set the script as parent.

local textLabelFloat = script.Template_GameFull -- Get access to it

... -- whatever you got between definition and first usage

local lbl = textLabelFloat:Clone() -- Just clone it, don't forget to set parent

This is an easier way to work with UI imo, since you can visually create it and edit it without having to write stuff in code for it.

Additionally, it is important you always parent after you change all the properties. I believe this is mostly important when doing stuff on the server, as the cost for replicating the changes is quite “high” compared to simply changing the properties first. However, it wouldn’t surprise me if it had impact on client only too.

Also: more lines of code does not always mean worse performance. While this is often true and a good rule of thumb, it’s good to know that it isn’t always the case.