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

Optimal way of variable defining? Is it wasteful?

Asked by 3 years ago
Edited 3 years ago

Hello, say I want to define input to a variable but I'm kinda skeptical about which is the optimal way of doing this...

A;

local key --variable defined only once which is in the start of playtest

UIS.InputBegan:Connect(function(input, gameProccessed)  
    key = input
end

or, B:

UIS.InputBegan:Connect(function(input, gameProccessed)
    local key = input --variable being defined everytime the event fires
end

I think A is the go-to when key is to be accessed outside of InputBegan's scope but what if it's only to be used inside?

Tips and explanations are greatly appreciated! <3

1
In my opinion, the First(A) is better when it comes to low-spec devices. Instead of storing a new data in the local RAM every time this event is fired, I prefer to store the local value only once, thus saving the RAM cashed memory drastically. This both won't make any difference when it comes to high-end devices. So, I highly recommend using the First(A) because to ensure the stability of the RAM. Shounak123 461 — 3y

2 answers

Log in to vote
2
Answered by
Speedmask 661 Moderation Voter
3 years ago
Edited 3 years ago

I’m not amazingly good with the lower levels of languages, but I am 90% sure that variable assignment only takes time at compile time. which is to say, when it is converted to bytecode, the memory for variables is already preallocated. not only that, but reused variables can be detected and optimized automatically, making no difference! in fact, the second one is even better because even after optimization the variable is found in an enclosed scope and it does not affect future processes with extra variables to look through. more importantly it is just easier to read.

note that this kind of thing is so miniscule that just having the variable outside and gobbling memory is slower than assigning it

you should never worry about variable assignments unless you are directly assigning memory yourself. which you do not do in lua.

edit: I would also like to mention which I find pretty neat, that the same goes for mathematical operations that only use constants. for example, you will never need to store Vector3.new(0, 1, 0) or math.sqrt, you could actually use than IN your equation, because they will be automatically converted to constants only once!

Ad
Log in to vote
1
Answered by
Xapelize 2658 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

They are the same if the value are being set, for example, a = 5. If you want to make the variable update everytime per scope, use B, otherwise, use A.

Answer this question