Assigning variables to objects makes referencing much faster than indexing, but you need to index to assign that variable. My question is, how many references to an object is the limit be before you should start using variables for that object?
Let me know if that was a bit confusing.
I searched the forum and found nothing.
NOTE: I’ve said this many times already, but I am NOT LOOKING FOR RECOMMENDED variable usage, but usage with the BEST PERFORMANCE. There are already tons of posts about recommended variable usage.
You should use a variable when something can be variable.
Other good times to use one is when you’re reusing a value that has a lengthy definition.
Now, don’t go using a variable for EVERYTHING.
Here is an example where it is stupid to do so:
local five = 5
print(10 / five)
print(15 * five)
Basically. Just use them where they make sense.
What if you only wanted to define something only two or three times? I’d definitely never do one, and your method makes sense, but I want to know what’s better performance wise even though it’s probably like a fraction of a second difference, that can add up in loops or something.
It’s not near a tenth of a second. It’s more like a millionth. Don’t be worried about a single variable declaration slowing down your code. What is more likely to slow it down is the actual definition of the value.
I remember reading somewhere that it was a pretty high wait time code wise. (a tenth of a second was an example I should stated that more clearly, it was slower than a hundredth of a second though)
Personally, I just use variables in order to increase readability especially when working with CFrames, and I have never thought in detail of the optimization benefits that come with using variables:
Here is an example of a code I saw, sorry if you recognize it:
--the CFrame calculated every heartbeat
Panel:SetPrimaryPartCFrame(CFrame.new(Camera.CFrame.Position) * CFrame.Angles(math.rad(game.Workspace.TrackerPart.Orientation.X), math.rad(game.Workspace.TrackerPart.Orientation.Y), math.rad(game.Workspace.TrackerPart.Orientation.Z)))
And here is what I would do, which is to just separate the CFrames being created.
local trackerPart = game.Workspace.TrackerPart--this is a constant
--the CFrame calculated every heartbeat
local cameraPositionCFrameOnly = CFrame.new(Camera.CFrame.Position)
local trackerPartOrientation = trackerPart.Orientation
local rotationCFrameOfTrackerPartOnly = CFrame.Angles(math.rad(trackerPartOrientation.X), math.rad(trackerPartOrientation.Y), math.rad(trackerPartOrientation.Z))
local goalCFrame = cameraPositionCFrameOnly*rotationCFrameOfTrackerPartOnly
Panel:SetPrimaryPartCFrame(goalCFrame)
Which one would you prefer to see? Although for this particular piece of code the correct way and shorter way to obtain the rotation CFrame is to do this:
Correct and shorter version
local trackerPart = game.Workspace.TrackerPart
local cameraPositionCFOnly = CFrame.new(Camera.CFrame.Position)
local rotationCFOfTrackerPartOnly = trackerPart.CFrame - trackerPart.CFrame.Position
local goalCFrame = cameraPositionCFOnly*rotationCFOfTrackerPartOnly
Panel:SetPrimaryPartCFrame(goalCFrame)
But yeah even if the variable is declared once and referenced once consecutively as long as I understand it should be ok.
Personally I’d prefer the one with more performance (why I’m creating this post) as long as I can understand it and it’s not crazy long.
I’d like to clarify that I’m looking for things more statistic wise. (Although clean scripts are very important, that’s not the topic of the post)
There’s microoptimization, and then there’s this.
Accessing local variables in Lua is very quick. In fact it is usually quicker to store a reference to a value in a variable than indexing a table or userdata for it everytime you need to use it.
A common optimization you might see is localizing global functions like math.max
so that the indexing could be cut out (however there are now optimizations in Luau that handles the resolving of these globals in a way that is already optimized, no more need to store them in a local variable)
Any performance hinderance at this level would be much more negligible than readability; any performance boosts you could get would not be worth the readability you lose.
I generally use them if I am going to use a certain reference more than once. I also use variables to avoid magic numbers for readability purposes.
There’s a certain point where the optimization is just going to be for naught - if your performance is truly negatively impacted simply by using variables, I believe there are other factors at play elsewhere.
Ok so I got curious here’s what I did,
I made the test function with a variable declaration
local function TestFunction()
local test = Vector3.new(1,0,1)
print(test)
end
And one that didn’t:
local function TestFunction()
print(Vector3.new(1,0,1))
end
Then put it through the basic tick test looping through 10,000 times:
local Start = tick() --Start time in seconds
for i = 1, 10000 do --For 1,000 times...
TestFunction() --Call TestFunction
end
print(tick()-Start) --End time in seconds
here’s the data I got which I plotted onto excel of the times.
Conclusion: Insignificant, why did I do this
You would mainly want to use a variable for the things that need defining, such as a value or a location of a folder, which you would need later on in your code;
local storage = game.ReplicatedStorage
local folder = storage:WaitForChild("Folder")
Then, once these are defined, you can use them freely;
folder.ChildAdded:Connect(function()
@cowsoncows @Crrustyy
So basically, this script
local Part = workspace.Part
Part.Transparency = 1
Is faster than this script?
workspace.Part.Transparency = 1
Also, @dthecoolest you put that on loop 10,000 times, not 1,000. It looks like it may have gotten laggy, the first data shows it’s a whole .4 seconds faster, and other sets of data shows it was even fast than that, and @SwagMasterAndrew thought it was a millionth of a second faster if anything (if my understanding of the data is correct, and my lag theory is correct)
I do not know if people have said this already but I use variables with things that constantly appear. Here’s an example.
local player = game.Players.LocalPlayer
if player.Name == "Dev" then
player:Kick("Banned")
else
print(player.Name.." ".."is not banned")
end
it would be annoying to keep having to write game.Players.LocalPlayer:Kick()
Not sure if I understand, I think you mean when you should use it. An example is:
when you are sending stuff to the server, example one what to do
game.ReplicatedStorage.RemoteEvent:FireServer(content)
an example of what NOT TO DO is:
game.ReplicatedStorage.RemoteEvent:FireServer(script.Parent.Text) -- in most cases
If this didn’t help check out Variables | Documentation - Roblox Creator Hub
Yes, read the title. That’s exactly what I mean.
Okay, but could you explain why or how many times you use that function, before it becomes slower than just indexing it?
Also the article just explains how variables work?
elaborate please I do not understand?
Say WHY you shouldn’t do that, don’t just say that you shouldn’t do that. By how many times you use that function before it becomes slower than indexing, means what it says, how many times should I reference that variable, so that it becomes more efficient than just indexing it. (The whole point of this post)
You don’t do it because it fills up space and also takes up more time/space when it could be put into a variable.
I don’t do what? Please restate I don’t know what you mean.
As an example, you don’t use “script.Parent.whatever” if you plan to use it many times so it takes less time in space. Creating a variable for “game.Workspace.Part” is much easier to understand than saying “game.Workspace.Part” every time you need to use it.