Fastest way to perform binary, decimal convertion using functions?

My current code is:

local function bin2Dec(str:string)
    return tonumber(str, 2)
end

local s = os.clock()
print(bin2Dec('1001')) --// 0.00035 to perform
local e = os.clock()
local a = e-s

local s = os.clock()
print(0b1001) --// 0.00025 to perform
local e = os.clock()
local b = e-s

print(a/b)

after comparing speed of both functions, turns out the second one is faster by 1.5 to 2 times. Is there a way to perform faster binary to decimal convertion using a function?

0b1001 isnt really a converting function, it’s part of Roblox’s lua interpreter, just like reading any other number.

tonumber is going to be the fastest conversion function since it is built into lua and heavily optimized in lower level languages like C and/or Assembly.

print is probably what is taking up most of your time to perform, but you need more tests per clock session for such small measurements like this “Time per 1000 conversions”

1 Like

Here is an example of testing the performance over 10,000 iterations, when benchmarking avoid using print during the test, it will always be a very slow function to call. Here I manage to get 10,000 runs in merely 2x the time you did for the first function call, I blame the print.

Notice the 0b1001 is an order of magnitude faster than the function, that’s because it doesn’t have to do much of anything, it’s just reading a number like usual. The function is actually performing a conversion.

local function bin2Dec(str:string)
	return tonumber(str, 2)
end

local s = os.clock()
for i = 0, 10_000 do
	bin2Dec('1001')
end
local e = os.clock()
local a = e-s
print("function   10,000: ", a) -- 0.0006157

local s = os.clock()
for i = 0, 10_000 do
	local null = 0b1001
end
local e = os.clock()
local b = e-s
print("convertion 10,000: ", b) -- 0.0000373 four zeros, much faster

print(a/b) -- b is 16.5 times faster
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.