Which piece of code do you think is more performant?

I have a code for a counting system that loops (1, 2, 3…10 then returns back to 1 and continue)
But there are 2 pieces of code that I have:

local counter = 1
local max = 5

while wait(1) do
   counter+= 1
   if counter > max then counter = 1 end
end

and

local counter = 1
local max = 5

while wait(1) do
   counter = math.clamp((counter + 1) % (max + 1), 1, max)
end

Which one do you think is more performant?

Code block 1 seems to do less operations per second. You can measure the performance by using tick(). I do not think that performance is very important here though, so I would just choose the solution that you think is the most simple and logical if I were you.

tick example:

local function measurePerformance(func)
    local t1 = os.clock()
    func()
    return os.clock() - t1
end

while wait(1) do
   print(measurePerformance(function()
      counter+= 1
      if counter > max then counter = 1 end
   end)
end
2 Likes

you should just break the loop once it gets to max

local counter = 1
local max = 5

while wait(1) do
    counter += 1
    if counter == max then break end
end

Thanks, but I would suggest that you use os.clock() instead of tick() because it’s deprecated

1 Like

I think you misunderstood the concept of this post. The point was to loop the number from min, max values, the while loop was just for visualization.

I think that I am getting old lol