32

Is it better to use NOT or to use <> when comparing values in VBScript?
is this:


If NOT value1 = value2 Then

or this:


If value1 <> value2 Then

better?

EDIT: Here is my counterargument.
When looking to logically negate a Boolean value you would use the NOT operator, so this is correct:


 If NOT boolValue1 Then

and when a comparison is made in the case of the first example a Boolean value is returned. either the values are equal True, or they are not False. So using the NOT operator would be appropriate, because you are logically negating a Boolean value.

For readability placing the comparison in parenthesis would probably help.

Tester101
  • 8,042
  • 13
  • 55
  • 78

4 Answers4

46

The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • I can't say how VBScript compiles it, but it also looks like two operations as opposed to one. – Powerlord Dec 15 '08 at 20:17
  • 1
    Apart from the fact that VBScript does not compile anything, it's indeed two operations. Additionally, NOT is (like the other logical operators in VBScript) a bitwise operator. 'Not 1' => '-2' – Tomalak Dec 15 '08 at 20:57
2

Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".

Here is a quick experiment to prove it:

StartTime = Timer
For x = 1 to 100000000
   If 4 <> 3 Then
   End if
Next
WScript.echo Timer-StartTime

StartTime = Timer
For x = 1 to 100000000
   If Not (4 = 3) Then
   End if
Next
WScript.echo Timer-StartTime

The results I get on my machine:

4.783203
5.552734
Regis Desrosiers
  • 537
  • 3
  • 13
1

Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.

If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.

0

The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as

If NOT (value1 = value2)

which just makes the use of the NOT keyword pointless.

hmcclungiii
  • 1,765
  • 2
  • 16
  • 27