I have also benchmarked this and these are my results
local function Assert(value)
assert(type(value) == "number", "Bad Argument" .. value)
end
local function If(value)
if type(value) ~= "number" then error("Bad Argument" .. value) end
end
local amount = 1000
local assertTotal = 0
for i = 1, amount do
local t = os.clock()
local a, b = 1, true
for i = 1, 1000 do
pcall(Assert, a)
a, b = b, a
end
assertTotal += os.clock() - t
end
assertTotal /= amount
task.wait()
local ifTotal = 0
for i = 1, amount do
local t = os.clock()
local a, b = 1, true
for i = 1, 1000 do
pcall(If, a)
a, b = b, a
end
ifTotal += os.clock() - t
end
ifTotal /= amount
print("Assert:", string.format("%.9f", assertTotal))
print("If ", string.format("%.9f", ifTotal))
Results:
-- Assert:
0.004660541
0.004596083
0.005090250
0.004749107
0.004602356
0.004767745
0.004852163
-- If
0.004702491
0.004715973
0.004451382
0.004726072
0.004471088
0.004481933
0.004517734
so I would say if is around 0.0002 seconds faster
but if I change the a and b values to always be numbers and change the error message to
"Bad Argument" .. value .. string.format("%.3f", value)
then I get results
-- Assert:
0.000970206
0.001223040
-- If
0.000116331
0.000109242
now we can see that if is around 0.0009 seconds faster
so we should not blame assert for this but blame the string functions because this performance impact will effect any function if your passing string that has had any work done to it not only assert
so the best way to use assert is to pass a simple string into it like this
assert(type(value) == "number", "Bad Argument")
and now the performance should be very close to if