Question

Alternative to Case

Asked by: a1x

I am using a case statement to take an input string and return a call to a function.

Example:
Select Case sSwitch
   Case "ABC"
      Return FunctionABC
   Case "XYZ"
      Return FunctionXYZ
...
End Select

The problem that i have is that there are several hundred cases, and it is in a loop, so it is taking a real long time..  Is there a VB.Net statement or construct that can search through a list of cases and return a function pointer? Or some other method that would be faster?

Thanks!

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
2006-06-22 at 15:43:25ID21896366
Tags

alternative

,

case

Topic

Microsoft Visual Basic.Net

Participating Experts
4
Points
415
Comments
12

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. Error locating a Domino Directory entry for certifier /OU=a…
    Hi everyone, Problem in domino server. My server & client are all in R6.5.1, the server is working fine, then suddenly alot of my clients can no longer connect to the server. They are recieving an error "Server Error: Entry not found in index". But if they use ...
  2. ABC Database
    Hi, Can anybody tell me what the term ABC Database refers to - is it a type of database or a company name. I looked on Google and there are lots of references to ABC Database, but nothing that I can see specifically focused on them. Links etc would be good. Many thanks, ...
  3. Constructing SQL "IN"
    I am trying to construct a call to a stored procedure with an where clause that includes an "IN" statement. I need help understanding how to construct the string passed into the stored procedure. If the string value is only one value (ie "B") it works fi...
  4. Table construction
    Can tables be constructed purely by CSS? Isn't "<table><tr><td></td></tr></table>" still the only dynamic way of output in HTML coding? Thanks.

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: JR2003Posted on 2006-06-22 at 16:12:48ID: 16964805

You could nest case statement and test the first character.

Select Case Left(sSwitch, 1)
   Case "A"
        Select Case sSwitch
           Case "ABC"
              Return FunctionABC
           Case "ABD"
              Return FunctionABD
        End Select
   Case "B"
        Select Case sSwitch
           Case "BCD"
              Return FunctionBCD
           Case "BDS"
              Return FunctionBDS
        End Select
   Case "C"
        Select Case sSwitch
           Case "CDE"
              Return FunctionCDE
           Case "CDF"
              Return FunctionCDF
        End Select
...
End Select

That way you reduce the average number test for each item.

 

by: FernandoSotoPosted on 2006-06-22 at 18:48:33ID: 16965370

Hi a1x;

Here is a way to do it without a Case statements.

    ' Declear pointer to a function using Delegate
    Delegate Function delFunction() As String

    ' Hash table to hold key / value pair
    Dim ht As New Hashtable

    Private Sub Form1_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        ' Load Hash table with the key and pointer to function to call
        Dim func As delFunction
        func = AddressOf FunctionABC
        ht.Add("ABC", func)
        func = AddressOf FunctionDEF
        ht.Add("DEF", func)

    End Sub

Then you can call them this way which is much faster then going through 100 case test.

    Private Sub Button1_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        Dim deleg As delFunction
        deleg = CType(ht("ABC"), delFunction)
        Console.WriteLine(deleg())
        deleg = CType(ht("DEF"), delFunction)
        Console.WriteLine(deleg())

    End Sub

    Private Function FunctionABC() As String
        Return "ABC"
    End Function

    Private Function FunctionDEF() As String
        Return "DEF"
    End Function

Fernando

 

by: SanclerPosted on 2006-06-23 at 03:30:32ID: 16967598

I doubt very much that it is your use of SELECT CASE that is causing your program to take "a real long time".  Try this

    Private Sub MakeCode(ByVal FileName As String)
        Dim sr As New StreamWriter(FileName)
        sr.WriteLine("Dim ticks As Long = Now.Ticks")
        sr.WriteLine("for a as integer = 1 to 1000")
        sr.WriteLine("dim b as string = cstr(a)")
        sr.WriteLine("select case a")
        For i As Integer = 1 To 1000
            Dim s As String = "Case " & Chr(34) & i.ToString & Chr(34)
            sr.WriteLine(s)
            s = "debug.writeline(" & Chr(34) & i.ToString & Chr(34) & ")"
            sr.WriteLine(s)
        Next
        sr.WriteLine("end select")
        sr.WriteLine("next")
        sr.WriteLine("Dim timelapse As Long = (Now.Ticks - ticks) / TimeSpan.TicksPerSecond")
        sr.WriteLine("MsgBox(timelapse)")
        sr.Close()
    End Sub

All it does is produce the code for a 1000 select case statement and code to loop through it looking for each value.  Although the values are derived from numbers they are expressed as strings to make it similar to your situation.

If you run that and then select all, copy and paste the text from the file it produces into a sub and run that sub I doubt that you will find it "taking a real long time".  Different systems will produce different results but, on mine, the result in the message box at the end was 2 seconds.

So my guess is that, if you want to reduce the time, you should be looking at the functions which your SELECT CASE routine is directing program flow to rather than at the SELECT CASE statement itself.

Roger

 

by: SanclerPosted on 2006-06-23 at 06:08:17ID: 16968598

It just occurred to me that, although I had added the line

        sr.WriteLine("dim b as string = cstr(a)")

so as to produce a "text" select case rather than a "number" select case, to line up with yours, I did not change

        sr.WriteLine("select case a")

to

        sr.WriteLine("select case b")

I've now done that and re-run.  The time on my system is now down to 1 second ;-)

Roger

 

by: a1xPosted on 2006-06-23 at 11:47:40ID: 16971679

Thanks FernandoSoto!

Exactly what I was looking for.  Tremendous increase in speed.

 

by: FernandoSotoPosted on 2006-06-23 at 12:52:09ID: 16972143

No problem glad I was able to help.

 

by: Idle_MindPosted on 2006-06-23 at 13:05:22ID: 16972236

You must have one LOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG Form1_Load() sub eh?....   =)

 

by: SanclerPosted on 2006-06-23 at 13:12:06ID: 16972288

"Tremendous increase in speed".  That's interesting.  I've just run comparative tests, using a similar approach to that outlined above.  That is, I wrote code to create 1000 instances of delegate functions and fill a hashtable with their addresses.  I then copied that code into a form and iterated through a 1000 loop to call each function once.  Here's the results.

Select case: 875 milliseconds
Select case: 594 milliseconds
Select case: 609 milliseconds
Select case: 578 milliseconds
Select case: 609 milliseconds
Select case: 797 milliseconds

Delegate: 1312 milliseconds
Delegate: 703 milliseconds
Delegate: 719 milliseconds
Delegate: 750 milliseconds
Delegate: 703 milliseconds
Delegate: 734 milliseconds

I must stress that I'm not arguing with Fernando's answer, or the award of points to him.  What matters is what works.

But I can't help wondering why.  It's just that, so far as I know, a SELECT CASE statement in fact works with, in the background, its own hashtable so I would have been surprised if, of itself, the upfront hashtable approach was any quicker.  My tests show that it isn't.  For all practical purposes it is the same.  So why, in the setting in this question, has it produced a "tremendous increase in speed"?

Any thoughts, anyone?

Roger

 

by: SanclerPosted on 2006-06-23 at 13:13:55ID: 16972304

Mike

Yes it is.  My intermediate code file was 118KB ;-)

Roger

 

by: a1xPosted on 2006-06-23 at 13:42:36ID: 16972531

Perhaps you are on Framework 2.0?  I am on 1.1.

Do you have the code to create the hash table functions?.  I'm curious.

 

by: SanclerPosted on 2006-06-23 at 14:51:21ID: 16972954

I did it in VB.NET 2003, Framework 1.1

Here's the code

    Private Sub MakeCode2(ByVal FileName As String)
        Dim sr As New StreamWriter(FileName)
        ' Declear pointer to a function using Delegate
        sr.WriteLine("Delegate Function delFunction() As String")

        ' Hash table to hold key / value pair
        sr.WriteLine("Dim ht As New Hashtable")

        sr.WriteLine("Private Sub Form1_Load(ByVal sender As Object,ByVal e As System.EventArgs) Handles MyBase.Load")

        ' Load Hash table with the key and pointer to function to call
        sr.WriteLine("Dim func As delFunction")
        For i As Integer = 1 To 1000
            sr.WriteLine("func = AddressOf Function" & i.ToString)
            sr.WriteLine("ht.Add(" & Chr(34) & i.ToString & Chr(34) & ", func)")
        Next
        sr.WriteLine("End Sub")
        For i As Integer = 1 To 1000
            sr.WriteLine("Private Function Function" & i.tostring & "() As String")
            sr.WriteLine("Return " & Chr(34) & i.ToString & Chr(34))
            sr.WriteLine("End Function")
        Next
        sr.Close()
        MsgBox("done")

    End Sub

The routine that I wrapped the iteration in, having used the above to generate the code which I copied into the form, was

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim ticks As Long = Now.Ticks
        Dim deleg As delFunction
        For a As Integer = 1 To 1000
            deleg = CType(ht(a.ToString), delFunction)
            Debug.WriteLine(deleg())
        Next
        Dim timelapse As Long = (Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond
        MsgBox(timelapse)
        Debug.WriteLine("Delegate: " & timelapse & " milliseconds")
    End Sub

The "Select Case" test just used the code from my earlier post, with the final output changed to debug and put in milliseconds.

Have fun with it.

Roger

 

by: SanclerPosted on 2006-06-23 at 15:07:16ID: 16973011

I've just converted the project to VB.NET 2005, Framework 2 and re-run the tests.  Here's the results for those.

Select case: 1484 milliseconds
Select case: 1266 milliseconds
Select case: 1359 milliseconds
Select case: 1297 milliseconds
Select case: 1266 milliseconds
Select case: 1297 milliseconds

Delegate: 1734 milliseconds
Delegate: 1266 milliseconds
Delegate: 1219 milliseconds
Delegate: 1188 milliseconds
Delegate: 1172 milliseconds
Delegate: 1172 milliseconds

In relative terms the two methods are still, for all practical purposes, the same - although the slight edge that Select Case had before Delegate has now.  But the most interesting thing is that the 2003 version is quite a bit faster than the 2005 version.  There's progress for you!

Roger

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...