Which Random Number Generator Is More Performant And Why?

I’m not entirely sure what the difference is between the two methods.

--!strict
local randomGenerator = Random.new()
local function getRandomNumber(a:number,b:number):number
    return randomGenerator:NextInteger(a,b)
end

print(getRandomNumber(-100,100))

--// Compare to math.random

print(math.random(-100,100))

Which method is more performant? And why? Furthermore, if you know a better more efficient method I’d like to hear it!

NextInteger will only provide integers and requires arguments. I believe it is more efficient than math.random

2 Likes

Doesn’t math.random only return integers likewise?

NextInteger is slightly slower than math.random, but NextInteger is more fair and can handle up to Int64 numbers while math.random can only handle up to Int32 numbers

The Int64 (64 bit lntegers) limit is around 9.2 quintiliion
while the Int32 (32 bit lntegers) limit is somewhere around 2 billion.

NextInteger can be used for more than math.random

1 Like

Not saying you’re wrong but how do you know this? Could you explain or source this conclusion? Just curious.

If I’m saying it right: benchmarking

local start = os.clock() -- start time

for i = 1,1e4 do -- runs 10,000 times
     -- whatever code here
end
local dt = os.clock() - start -- the elasped time (or speed)
print(dt)

You just compare the values, and it would show you their speed differences, you would have to run multiple times to be sure.

1 Like