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

Is it more efficient to use a variable or to access the property each time?

Asked by 5 years ago

So the question might seem a little weird but hear me out. Recently when I posted a question with a script attached some person commented saying something like: "Why are you using the variable plrName instead of just doing plr.Name each time?" Note: local plrName = plr.Name. So I started changing my scripts to reflect what the person said. Today I was thinking and wondered if it was better to use the variable anyway. The reason: Every time you do .Name aren't you accessing a property of player? If so, is it not more effective and efficient to store the string in a variable so you are not accessing it each time? I do think that if you just needed to use the player's name a few times, it might be more efficient to do .Name. However, I am using it many times and want to know what the better method is. Does it even make that big of a difference in performance? Thanks!

2 answers

Log in to vote
1
Answered by 5 years ago

I'd make direct accesses to the property. If I define a property in a variable, it will not hold a reference to the property, it will instead hold the property's value. It will not update if the value changes, so if you wanted it to change you'd have to keep redefining the variable so it is up to date. When you make a direct access to a property, it will always be up to date.

local name = workspace.Brick.Name
print(name) --> Brick
workspace.Brick.Name = "Part" 
print(name) --> Brick
print(workspace.Brick.Name) --> Part

Making variables to object references like script.Parent is usually, as not many times does a Parent get reassigned.

0
The plrName variable never changes. I want to know about efficiency, not really about the potential dangers. I know that when something is changing you should access it directly. In this instance though, nothing will be changing or the world will have ended. User#21908 42 — 5y
0
I don't think efficiency would be a factor in that. But if you really cared you could run a benchmark perhaps. User#19524 175 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

They both work, but the variable one will let you put a shorter amount of code each time, plus you are writing it multiple times.

The point is I think variable is better, -DominusInfinitus (I hope this works out for you)

0
I know they both work and the typing is not the issue. This really is not what I was looking for in an answer. Sorry man. User#21908 42 — 5y
0
its is fine RetroGalacticGamer 331 — 5y

Answer this question