Hello, so I want to know whether declaring a variable outside a function will save me any time or am I wasting my time doing this? For more context I have a function which runs thousands of times and I want to optimize the code to the absolute limit. I have these two functions:

-- Demo 1:
local scaleSize = 10
function GenerateVectorWithScaleSize()
local vector = Vector3.new(0,scaleSize,0)
end
-- Demo 2:
function GenerateVectorWithoutScaleSize()
local vector = Vector3.new(0,10,0)
end

Demo 1 has a declared variable outside the function (10), and Demo 2 has no variable with just the number in the Vector3.

Let’s say they run in a loop somewhere a few thousand times which would run faster?

Its a micro-optimisation, barely does anything but this would be useful if you used that number a few times in a few different functions. Also since it could be easiler to configure

A truly negligible amount, not even really worth thinking about. It would also only ‘save’ time if you use that variable multiple times in different functions. Otherwise you’re just using up memory for no reason.

If your code is slow, you should look at ways of improving your approach. Remember that the Time Complexity is usually that of the slowest part of your algorithm. If you have a slow for loop that’s O(n^2) anything you do to micro optimise will make very little difference.

I ran a benchmark, this should answer your question.

local scaleSize = 10
local function benchmarkOne()
local var = Vector3.new(0, scaleSize, 0)
end
local function benchmarkTwo()
local var = Vector3.new(0, 10, 0)
end

This test was ran 10,000 iterations, meaning those two functions were called 10,000 times. I then ran the test 100 additional times, and collected the average of both results.

Meaning out of 1,000,000 iterations, the test concluded the following:

Average Benchmark One: 0.00021558284759521485
Average Benchmark Two: 0.00021160840988159179

Which concludes- in a 10,000 iterations there is a difference between the two of; 0.0000034 seconds. (on average)

In other words, do whatever you want. One is going to be (0.0000034 * 0.01) slower, and that could just be my test being a hair faulty.

local vector = Vector3.new
local function benchmarkOne()
local var = vector(0, scaleSize, 0)
end
local function benchmarkTwo()
local var = Vector3.new(0, 10, 0)
end

With the results being; after 10,000 iterations, ran 100 times, for an average.

Average Benchmark One: 0.0005368852615356446
Average Benchmark Two: 0.0002115321159362793

Meaning in 10,000 iterations, on average storing a ‘vector.new’ as a variable, is actually 0.0003 slower.

Once more, don’t bother worry about this though, not enough to make a difference.