Lag Spikes when Instantiating new Objects?

Hello all!

I’m having a very weird issue. The following code has not been altered lately (besides debug attempts), yet now it is causing severe lag spikes when called. A call to this function is performed every 2 seconds and the game freezes up when this is done. This never happened before.

Is there some quirk to :Clone() that causes lag? Could it be the position randomizer?

Here is the code:

local newFly = script.Firefly:Clone()

local base = RenderedPlot

local newPos = Vector3.new(
	math.random(base.Position.X - (base.Size.X / 2), base.Position.X + (base.Size.X / 2)),
	base.Position.Y + base.Size.Y + 5,
	math.random(base.Position.Z - (base.Size.Z / 2), base.Position.Z + (base.Size.Z / 2))
)

newFly.Parent = flyHolder
newFly.Position = newPos

local newSize = Vector3.new(
	math.random(5, 10) / 10, 
	math.random(5, 10) / 10, 
	math.random(5, 10) / 10
)

newFly.Size = newSize

I am annoyed that this is occurring out of nowhere. Any feedback appriciated.

Parenting the object after setting all of the properties has performance benefits, maybe you could try doing that?

That didn’t seem to help, unfortunately.

This is the microprofiler. That spike you see is every time the function is called.

Is it possible that you can attach a .rbxm file with the assets needed for this script to work? Alternatively, you could try testing this by itself in a separate game to see if it’s what’s causing the problem.

Ill describe how the system operates:

The game initializes with a core script that loads required modules and calls a prewarm() function. This loads the assets.

The game then runs the launch() function. Starting the execution of each script on its own thread.

One of the scripts that gets launched is a PlotManager. Which spawns said fireflies every x seconds.

The code that you see there sits inside of a function that spawns the firefly.

So theoretically there shouldn’t be any reason this is freezing the game. One theory I have is that there are too many objects in the game simultaneously. But all of these objects are anchored. Very bizarre.

1 Like