Which causes less laggy?
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
By a miniscule amount in some extraneous circumstances, usually the functions and methods that are native to the base language run faster, so math.random() since it is native to Lua.
Random vs math.random
Random
is slower than math.random()
, however its more efficient with decimals, and supports 64 bit Integers (whole numbers up to 2^63)
math.random()
is faster than Random
, however it only supports 32 Bit Integers (whole numbers up to 2^31, this is also why it gives an error for when you give it a really high number)
Keep in mind, that math.random()
and Random
are NOT the same thing.
Random
contains a serious of functions for you to use when requiring psuedo-randomness.
Random
contains
-
:NextNumber()
which is a random decimal between 0 and 1 -
:NextInteger()
a random number between X and Y up to 2^63; -
:NextUnitVector()
a random vector direction -
:Shuffle()
randomizes a table
math.random()
serves two uses, which are
- Grabbing an Integer within a certain field (add 2 variables, or 1 for only a max value)
- Grabbing a decimal between 0 and 1. (execute
math.random()
without arguments)
math.random()
just like Random
has support for Seeds, being changable with the function math.randomseed()
, In order to apply a seed to Random
, you give a number argument inside of Random.new()
.
How we test speed
We test functions, and code using a concept known as a benchmark, where the run code over a thousand times and capture the time it took.
local start = os.clock() -- for accurate time
for i = 1,10000 do -- run for 10,000 iterations
-- code to run
end
local stop = (os.clock() - start); -- the amount of time it took
print(stop) -- use this to check for speed differences
Using this we are able to see how long it takes to run specific code a certain amount of times. If the time difference is only a few microseconds, then a performance difference will be negligable, which is why most programmers typically say to ignore those type of circumstances. If time between time is way bigger than the other, the ladder is probably more efficient and performant to use.
For the case of Random
, it will typicalaly take about 1 - 3 milliseconds to run for many iterations, while with math.random()
will be at around 0.5 - 0.9 milliseconds, so the difference is pretty much negligable under most circumstances.
For 60 FPS, it takes around 17 milliseconds to run a single frame, so you are using only 5% of that frame to run Random
, which should not cause any performance issues.
Summary
Both serve similar purposes, but are two different things, and just because one is faster doesnt always mean its the best, but its ultimately what you decide to use it for.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.