Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I optimize this function?

Asked by
Trew86 175
5 years ago
function UpdateSpeed()
while true do
wait(0.1)
if plr then
local Speed = math.floor(Seat.Velocity.Magnitude)
Gui.Frame.SpeedLabel.Text = (Speed).."/"..(maxSpeed)
else
    break;
end
end
end

Having while loops to update the speed meter works, but seems to increase lag, when I remove the function the vehicle seems to move faster. Is there any alternatives to while loops that I could use to update the text of a speed meter based on the current speed of a part?

0
.Changed DinozCreates 1070 — 5y
0
`.Changed` isn't fired on Velocity, or position EpicMetatableMoment 1444 — 5y
0
Neither is `GetPropertyChangedSignal("Velocity")` EpicMetatableMoment 1444 — 5y
0
You could try checking the speed every `.5` seconds which would help boost preformance EpicMetatableMoment 1444 — 5y
View all comments (7 more)
0
You could also set a variable for `math.floor` outside of the `UpdateSpeed` function so you don't need to spend more time indexing. EpicMetatableMoment 1444 — 5y
0
Also concatenation is slow, you can try use `:format` with a `%d%d` pattern. `SpeedLabel.Text = ("%d/%d"):format(Speed, maxSpeed)` EpicMetatableMoment 1444 — 5y
0
Also set a variable outside the `UpdateSpeed` function for `SpeedLabel` so you can index it faster EpicMetatableMoment 1444 — 5y
0
Why not use `plr` as the condition for the while loop, instead of using an if? `while plr do` TheeDeathCaster 2368 — 5y
0
good thinking @thee EpicMetatableMoment 1444 — 5y
1
If the speed hasn't changed by more than 0.1 for more than 2 seconds or something, decrease the frequency of polling. You get the resolution of high polling, without wasting cycles doing nothing if it's not moving, or has been moving at a constant speed for a while. fredfishy 833 — 5y
1
Alternatively, you could bind a function :GetPropertyChangedSignal("Throttle"), and only run the loop until the throttle goes back to 0. fredfishy 833 — 5y

1 answer

Log in to vote
0
Answered by
metryy 306 Moderation Voter
5 years ago
Edited 5 years ago

You can use RenderStepped that fires everytime a frame is rendered in place of the while true do loop. Example:

local function UpdateSpeed()
    if plr then
        local Speed = math.floor(Seat.Velocity.Magnitude)
        Gui.Frame.SpeedLabel.Text = (Speed).."/"..(maxSpeed)
    else
        break -- Commas are ignored by the Lua interpreter so it's not necessary to put one here
    end
end

game:GetService("RunService").RenderStepped:Connect(UpdateSpeed)

Hope this helps.

Ad

Answer this question