Question

IF Statement vs Select Case Statement

Asked by: Mr_Fulano

Hi, I'm using VB 2005, WinForms. I have an application that performs a lot of very complex mathematical calculations. It's running a bit slow, because of how much it has to calculate. I'm trying to tweak my code so that I can make it as efficient as possible. One of the questions that I'm facing is whether to use an "IF Statement" or a "Select Case Statement" in a situation very similar to the one presented below:

If x > 0 AND x < 10 Then
 Do this....
  If x > 11 AND x < 20 Then
   Do this....
    If x > 21 AND x < 30 Then
     Do this....  
      If x > 31 AND x < 40 Then
        Do this....
etc...all the way to 100.

OR...use

Select Case x
 Case x > 0 AND x < 10
  Do this....
 Case x > 11 AND x < 20
  Do this....
 Case x > 21 AND x < 30
  Do this....
 Case x > 31 AND x < 40
  Do this....
 Case x > 41 AND x < 50
  Do this....
etc...to 100.

I would like to use the logic test that is less time consuming, but obviously just as accirate.

Thanks,
Fulano

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-04 at 16:42:27ID24873157
Tags

VB 2005

,

VB 2008

Topics

Microsoft Visual Basic.Net

,

.NET

Participating Experts
2
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Mathematical Calculation in HTML
    How can I do mathematical calculation inside a HTML page? On the click of a button on the HTML page, I need to do some mathematical evaluation and return some value which is to be used in the HTML page. For example something of the type, <SCRIPT> function mathematics...
  2. Mathematical solution needed
    How can it be mathematical proven that you can reach a goalvalue Y from a startvalue X by using the following rules (f & g)? f. X * 3 g. floor(X/2) ex. If X=9, floor(9/2)=4 Ex. X=15, Y=4 can be reached true "ggfg" g. 15/2=7 g. 7/2=3 f. 3*3=9 g. 9/2=4 I nee...
  3. Mathematics Calculator
    Is there any free component for VB.NET 2003 on mathematics calculator ? i.e. pass a mathematics formula to a function and will return a result e.g. pass "(1+2)*10/5" to function then return 6 as result

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: 930913Posted on 2009-11-04 at 16:48:25ID: 25745815

This should work if x is discreet. Is each case completely different coding? If not, then you should be able to make it even more efficient.

Select Case x
 Case <0
 Case < 10
  Do this....
 Case < 20
  Do this....
 Case < 30
  Do this....
 Case < 40
  Do this....
 Case < 50
  Do this....

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: Mr_FulanoPosted on 2009-11-04 at 16:55:23ID: 25745844

Hi 930913,

Each Case or calculation is exactly the same, with a different variable. However, everything builds on that variable, so I can't really set up too many "pre-calculated" values - that's what makes it slow-er than I'd like it to be.

Fulano

 

by: Mr_FulanoPosted on 2009-11-04 at 16:56:44ID: 25745851

Hi 930913, actually, I take that back...each case is a slightly bit different, but I'd say that they are all about 80% similar.

Fulano

 

by: 930913Posted on 2009-11-04 at 17:02:41ID: 25745874

x Mod 10
will return 0-10 depending what x is (5>0, 24>2, 59>5, etc)
Could you make one calculation for each case using this as a variable?

 

by: Mr_FulanoPosted on 2009-11-04 at 20:16:20ID: 25746732

Hi 930913,

>>x Mod 10 - will return 0-10 depending what x is (5>0, 24>2, 59>5, etc)
Could you make one calculation for each case using this as a variable?<<

hhhmm....I guess I could if I knew how it works. What is it called? (simply "Mod")

Can you give me a simple example of how you would use it? Let say my equation was something like: 3x +2 = y.

(5>0, 24>2, 59>5, 2>4)
So, if I did something like "x Mod 4", would my equation be:

    3(2)+2 = y ; thus y = 8

Yes,... no,... maybe....

Also, how do you declare all that?

Thanks,
Fulano

 

by: Mr_FulanoPosted on 2009-11-04 at 21:51:28ID: 25747041

Hi 930913,

Here's something interesting...(which I should have tested in the first place).

I conducted a test - the same code - the same number of calculations, where the only difference was performing the logic with an IF statements vs a Select Case Statements. Below are the results:

Using IF Statements:
---------------------------------------------
Start Time: 11/5/2009 12:45:03 AM
End Time  : 11/5/2009 12:45:36 AM
Time Elapsed :  32.859375 (Seconds)   or  0.54765625 (Minutes)====================================================

Using Select Case Statements:
--------------------------------------------
Start Time: 11/5/2009 12:43:17 AM
End Time  : 11/5/2009 12:43:50 AM
Time Elapsed :  32.9375 (Seconds)   or  0.548958333333333 (Minutes)
====================================================

Its close, but the IF Statement is faster by about a thousands of a minute.  It's a lot closer than I expected it to be and maybe not worth the trouble to recode.

I'm not sure why this is....do you have any ideas?

Thanks,
Fulano




 

by: CodeCruiserPosted on 2009-11-05 at 03:07:21ID: 25748287

Both If and Case work by evaluating the expression to either true or false so there should not be much difference in the performance.

 

by: 930913Posted on 2009-11-05 at 07:05:21ID: 25750188

Hmmm. Try it a few times and take an average.
Also, take a look at this site: http://www.aivosto.com/vbtips/vbtips.html#optimize

 

by: Mr_FulanoPosted on 2009-11-05 at 20:41:52ID: 25756646

Gentlemen, thanks for the input. -- Here is another test of a set of calculations that is about 15 times the amount of the original test above. This test took approximately an hour, but CodeCruiser is correct (as usual) in saying that the times will be very close indeed. The difference is about 27 seconds.

In this case however, the Select Case outpaced the IF Statement (not by much), but it did.

Using IF Statements:
---------------------------------------------
Start Time: 11/5/2009 10:31:59 PM
End Time  : 11/5/2009 11:30:48 PM
Time Elapsed :  3528.671875 (Seconds)   or  58.8111979166667 (Minutes)
====================================================

Using Select Case Statements:
--------------------------------------------
Start Time: 11/5/2009 8:08:36 PM
End Time  : 11/5/2009 9:06:58 PM
Time Elapsed :  3501.765625 (Seconds)   or  58.3627604166667 (Minutes)
====================================================

Quite interesting...now the question really becomes, why use one over the other if the speed (which is how I'm measuring efficiency) is not the prime factor? -- Anyone wish to opine?

Thanks,
Fulano

 

by: 930913Posted on 2009-11-05 at 21:05:44ID: 25756722

I would hazard a guess that it is for user readability. Lots of if else statements could get confusing.

 

by: CodeCruiserPosted on 2009-11-06 at 01:00:05ID: 25757641

I think Case statement is very useful when you are comparing integer type values. For example

            Select Case t
                Case 1
                    ...
                Case 2
                    ...
                Case 3
                    ...
            End Select

Where as IF is more readable where you are evaluating big expressions such as
If (Not String.IsNullOrEmpty(mystring)) AND (cbtest.Checked) Then

 

by: 930913Posted on 2009-11-06 at 06:08:10ID: 25759179

Aha! If you use big expressions in multiple if statements, it will need to execute it each time whereas it only needs to evaluate it once in a select case.

 

by: CodeCruiserPosted on 2009-11-06 at 06:11:38ID: 25759210

>whereas it only needs to evaluate it once in a select case.

How about
            Dim T As Integer
            Select Case T
                Case (T < A + B) And (T > B + C)

                Case (T > B + C) And (T < C + A)

            End Select

???

 

by: 930913Posted on 2009-11-06 at 06:27:23ID: 25759340

It will only need to evaluate T once here. If T was a big, complex expression it would remove the need to evaluate two times e.g.
If BigExpression = 1 Then
Else If BigExpression = 2 Then
Else If BigExpression = 3 Then

 

by: Mr_FulanoPosted on 2009-11-18 at 20:45:26ID: 25857582

Gentlemen, sorry for the delay. I got sidetracked onto something else.

I think this was an interesting debate and I appreciate your help. In the end, I went with the Case Statement for sake of clarity.

Thanks again,
Fulano

 

by: Mr_FulanoPosted on 2009-11-18 at 20:46:18ID: 31650315

Great help!!!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...