Is This More Efficient to Use

I was coding and was too lazy to type something like:

if var == false then
      var = true
else
      var = false
end

So instead, I did this:

var = not var

Is that more efficient in terms of performance, or speed? Keep in mind this is a Boolean

The difference will be negligible, but I would personally use the second one because it’s better for readability. Ternary operators will generally be more efficient than if statements though.

I also did some benchmarks.

Code:

local startingTime = os.clock()
local var = false

for i = 1, 100000000 do
	var = not var
end

print("ternary operator: ".. os.clock() - startingTime)

local var = false

local startingTime = os.clock()

for i = 1, 100000000 do
	if var then
		var	= false
	else
		var = true
	end
end

print("if statements: ".. os.clock() - startingTime)

Output:

ternary operator: 0.2924475999971037
if statements: 0.6549763000002713

Edit: I misclassified it as a ternary operator, apologies.

1 Like

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