Code review for optimization

Hello,

I’ve just finished doing my client-sided part for my NPC framework and I realized that I had to run something on renderstepped. Since I am not experienced with optimizing scripts, may someone help me find things I can optimize? Thank you for reading.

the code (run on renderstepped)

local final = CF(waypoints[self.index].Position)

if vector.X < CAM.view.X + MARGIN and vector.X > -MARGIN and vector.Y < view.Y + MARGIN and vector.Y > -MARGIN then
    final *= OPPOSITE
    self:show()
else
    self:hide()
end

self.root.CFrame = final:lerp(final, MOVE_CF_RATIO * 60 * dt)

if get_dist(self.root.CFrame.Position, final.Position) < 5 then
    self.index += 1
end
if self.index >= #ways then 
    done:FireServer(self.group)
    self.index = 1
    render_connection:disconnect()
    return 
end    

I recommend stepping away from RenderStepped but instead go with Heartbeat as it seems like your code is handling positions and CFrames and Heartbeat fires after physics simulation, therefore you’ll get more accurate results.

Only use render stepped when you want to handle something before a frame is rendered, but in this case, it is unneeded.

Keep in mind that disconnect is deprecated in favour of Diconnect. There is not much that can be optimized.

2 Likes