Solved

what's quicker? equal to or not equal to

Posted on 2006-11-02
16
510 Views
Last Modified: 2010-04-23
Hi

This is a question for my curiosity.

Lets say i wanted to perform an action  (Action a) if  a particular variable was equal to a value of x and perform another action (action b) otherwise. I could do this 2 ways

If var = x then
action a
else
action b
end if

if var != x
action b
else
action a
end if

my common sense would tell me the first is quicker but computers have been known to do things i don't understand for optimisation reasons. Which one is quicker?

thankd
andrea
0
Comment
Question by:andieje
  • 6
  • 3
  • 3
  • +2
16 Comments
 

Author Comment

by:andieje
ID: 17858446
Perhaps it's also different depending on what you're comparing. Perhaps in  a string comparison number 2 is quicker .
0
 
LVL 35

Expert Comment

by:YZlat
ID: 17858470
for string comparison you'll have to use String.Compare
0
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 250 total points
ID: 17858475
With modern CPU, the answer is: put the condition the way so it turns true the most times.

reason:
  CPU today compute in advance, while on IF's, they continue in advance on the most probable way.
  usually, that is the first one in IF, so the condition to evaluate to true.
  if the condition evaluates to the other value (false), then the code that has already been computed in advance will be thrown away in the CPU cache and the other part will be avaluated.

in most IF conditions it does not really matter, though.
0
 
LVL 35

Expert Comment

by:YZlat
ID: 17858476
what language are yoo using though?
0
 
LVL 35

Assisted Solution

by:YZlat
YZlat earned 50 total points
ID: 17858487
example:

Dim str1 As String = "ppp"
Dim str2 As String = "ccc"
Dim res As Int16 = String.Compare(str1, str2)
Console.WriteLine("First result:" + res.ToString())
str2 = "ttt"
res = String.Compare(str1, str2)
Console.WriteLine("Second result:" + res.ToString())
str1 = "ttt"
res = String.Compare(str1, str2)
Console.WriteLine("Third result:" + res.ToString())
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 17858817
Hi andieje;

Here is some test code to test the speed of each version using VS .Net 2005.

My test results where based on 100,000,000 times through the loop on each.
    The Eauals Version
    Numeric code run time 460 ms
    String code run time 1848 ms

    The Not Eauals Version
    Numeric code run time 470 ms
    String code run time 2798 ms

Sample Code

        Dim sw1 As New Stopwatch
        Dim sw2 As New Stopwatch
        Dim Maxloops As Integer = 100000000
        Dim var1 As Integer = 100
        Dim Var2 As String = "ABC"
        Dim msg As String

        sw1.Reset()
        sw1.Start()
        For idx As Integer = 0 To Maxloops
            If var1 = 100 Then
                var1 += 1
            Else
                var1 -= 1
            End If
        Next
        sw1.Stop()

        sw2.Reset()
        sw2.Start()
        For idx As Integer = 0 To Maxloops
            If Var2 = "ABC" Then
                Var2 = "ABCD"
            Else
                Var2 = "ABC"
            End If
        Next
        sw2.Stop()

        msg = "Numeric code run time " & sw1.ElapsedMilliseconds.ToString & " ms" & vbCrLf & _
            "String code run time " & sw2.ElapsedMilliseconds.ToString & " ms"
        MessageBox.Show(msg, "Equals Version")

        sw1.Reset()
        sw1.Start()
        For idx As Integer = 0 To Maxloops
            If var1 <> 100 Then
                var1 += 1
            Else
                var1 -= 1
            End If
        Next
        sw1.Stop()

        sw2.Reset()
        sw2.Start()
        For idx As Integer = 0 To Maxloops
            If Var2 <> "ABC" Then
                Var2 = "ABCD"
            Else
                Var2 = "ABC"
            End If
        Next
        sw2.Stop()

        msg = "Numeric code run time " & sw1.ElapsedMilliseconds.ToString & " ms" & vbCrLf & _
            "String code run time " & sw2.ElapsedMilliseconds.ToString & " ms"
        MessageBox.Show(msg, "Not Equals Version")


Fernando
0
 
LVL 34

Assisted Solution

by:Sancler
Sancler earned 50 total points
ID: 17860047
Fernando

I think the logic of the testing code may have gone a bit wrong.  I think the idea is that it should toggle the tested value so that it is true and false on alternate passes through the loop.  It does that on the Equals version.  But to make it do it on the Not Equals version, the operations need to be put the other way round from the Equal version.

        sw1.Reset()
        sw1.Start()
        For idx As Integer = 0 To Maxloops
            If var1 <> 100 Then
                var1 -= 1
            Else
                var1 += 1
            End If
        Next
        sw1.Stop()

        sw2.Reset()
        sw2.Start()
        For idx As Integer = 0 To Maxloops
            If Var2 <> "ABC" Then
                Var2 = "ABC"
            Else
                Var2 = "ABCD"
            End If
        Next
        sw2.Stop()

I've tried it with that, and the results are significantly different:-

Equals Version
Numeric code run time 354 ms
String code run time 1654 ms
Not Equals Version
Numeric code run time 1104 ms
String code run time 1648 ms

Equals Version
Numeric code run time 362 ms
String code run time 1632 ms
Not Equals Version
Numeric code run time 1181 ms
String code run time 1623 ms

Equals Version
Numeric code run time 363 ms
String code run time 1640 ms
Not Equals Version
Numeric code run time 1089 ms
String code run time 1627 ms

Equals Version
Numeric code run time 357 ms
String code run time 1629 ms
Not Equals Version
Numeric code run time 1146 ms
String code run time 1658 ms

For strings, it doesn't seem to make any real difference.  But for integers, it looks like a factor of about three.

Does my revision make sense?  Or have I missed something?

Roger
0
 
LVL 62

Assisted Solution

by:Fernando Soto
Fernando Soto earned 150 total points
ID: 17861149
Hi Roger;

You are correct about the Not Equals version. When I wrote the Equals version I copied and past the code charged the var names to reflect for the new test but neglected to change the test around. Having said that I would not have expected to see much of a difference in the test results because it is doing one comparison and one assignment through each loop.

 My new test results with Rogers correction:

Equals Version
Numeric code run time 455 ms
String code run time 1867 ms
Not Equals Version
Numeric code run time 457 ms
String code run time 1916 ms

Equals Version
Numeric code run time 459 ms
String code run time 1872 ms
Not Equals Version
Numeric code run time 458 ms
String code run time 1909 ms

Equals Version
Numeric code run time 459 ms
String code run time 1855 ms
Not Equals Version
Numeric code run time 473 ms
String code run time 1864 ms

Equals Version
Numeric code run time 453 ms
String code run time 1870 ms
Not Equals Version
Numeric code run time 465 ms
String code run time 1880 ms

I do not know how to explain the different in results between what you got and what I just got.

Thank you for keeping me honest. I do not like posting bad code and I should have given it a closer look.

Fernando ;=)
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 34

Expert Comment

by:Sancler
ID: 17863233
Fernando

I agree that the difference that I reported on the Numerical side looked odd, so I've been experimenting a bit.  So far as I can tell, it arises from the StopWatch.  The "real" results should be those you show: that is, that there should be no appreciable difference between testing for Equal or Not Equal.

It seems clear that - on my system at least - StopWatch.Stop doesn't always take immediate effect.  I haven't yet worked out the distinguishing features between when it does work OK and when it doesn't and, given your results, it does seem to be system-dependent at least to some extent.

I personally still tend to use Ticks, so this is a phenomenon I hadn't noticed before.  But I'll dig into it a bit more and post here again if I have any positive findings.

Roger
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 17863447
Thanks Roger for your efforts.

Fernando
0
 
LVL 34

Expert Comment

by:Sancler
ID: 17865372
Fernando

This has really raised a completely different issue, so I've posted a specific question.  It's here

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_22047746.html

Roger
0
 

Author Comment

by:andieje
ID: 17871176
Thanks very much everyone. That was an interesting question
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 17877386
Always willing to help out. ;=)
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 17895391
Hi andieje;

Is there anything else that we can help with this question?

Fernando
0
 

Author Comment

by:andieje
ID: 17994921
no, it was just for my curiosity :)

but i need your help with my processes again!!! please let me know when you around and i will post a question. i have posted a few before but you werent around so they were ignored :(
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 17995527
Hi andieje;

I am generally around some part of each day.

Fernando
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now