Visual Basic Q&A

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘module option’

How To Improve String Concatenation Performance

Symptoms
When concatenating large strings on the order of 50kb or larger (for example, building an HTML table from a database), the length of time to complete can become quite long as the string gets larger. This article demonstrates an alternative to normal concatenation that can improve performance for large strings by 20 times or more.
Resolution
When performing repeated concatenations of the type:

For I = 1 To NDest = Dest & SourceNext N the length of time increases proportionally to N-squared. Therefore, 1000 iterations will take about 100 times longer than 100 iterations. This is because Visual Basic does not just add the Source characters to the end of the Dest string; it also performs the following operations:
Allocates temporary memory large enough to hold the result. Copies Dest to the start of the temporary area. Copies Source to the end of the temporary area. De-allocates the old copy of Dest. Allocates memory for Dest large enough to hold the result. Copies the temporary data to Dest. Steps 2 and 6 are very expensive and basically result in the entire concatenated result being copied twice with additional overhead to allocate and de-allocate memory.
This article details a method using the Mid$ statement and pre-allocating memory in larger chunks to eliminate all but step 3 above for most of the concatenation phase.
WARNING: ANY USE BY YOU OF THE CODE PROVIDED IN THIS ARTICLE IS AT YOUR OWN RISK. Microsoft provides this code “as is” without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.
Step-by-Step ExampleType the following code into a module:

Option Explicit’ For 16-bit products, uncomment the next three lines by removing the’ single quotes and add a single quote to comment out the following’ three lines.’Const ConcatStr = “ABC”‘Const ccIncrement = 15000′Declare Function GetTickCount Lib “USER” () As LongConst ConcatStr = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”Const ccIncrement = 50000Private Declare Function GetTickCount Lib “KERNEL32″ () As LongDim ccOffset As LongSub StdConcat(ByVal LoopCount As Long)Dim BigStr As String, I As Long, StartTick As LongStartTick = GetTickCount()For I = 1 To LoopCountBigStr = BigStr & ConcatStrNext IDebug.Print LoopCount; “concatenations took”;Debug.Print GetTickCount() – StartTick; “ticks”End SubSub Test_Concat()Debug.Print “Using standard concatenation”StdConcat 1000StdConcat 2000StdConcat 3000StdConcat 4000StdConcat 5000Debug.PrintDebug.Print “Using pre-allocated storage and pseudo-concatenation”MidConcat 1000MidConcat 2000MidConcat 3000MidConcat 4000MidConcat 5000End SubSub Concat(Dest As String, Source As String)Dim L As LongL = Len(Source)If (ccOffset + L) >= Len(Dest) ThenIf L > ccIncrement ThenDest = Dest & Space$(L)ElseDest = Dest & Space$(ccIncrement)End IfEnd IfMid$(Dest, ccOffset + 1, L) = SourceccOffset = ccOffset + LEnd SubSub MidConcat(ByVal LoopCount As Long)Dim BigStr As String, I As Long, StartTick As LongStartTick = GetTickCount()ccOffset = 0For I = 1 To LoopCountConcat BigStr, ConcatStrNext IBigStr = Left$(BigStr, ccOffset)Debug.Print LoopCount; “pseudo-concatenations took”;Debug.Print GetTickCount() – StartTick; “ticks”End Sub In the Debug/Immediate Window, type Test_Concat, and hit the Enter key.
The results will look similar to:

Using standard concatenation1000 concatenations took 2348 ticks2000 concatenations took 8954 ticks3000 concatenations took 20271 ticks4000 concatenations took 35103 ticks5000 concatenations took 54453 ticksUsing pre-allocated storage and pseudo-concatenation1000 pseudo-concatenations took 82 ticks2000 pseudo-concatenations took 124 ticks3000 pseudo-concatenations took 165 ticks4000 pseudo-concatenations took 247 ticks5000 pseudo-concatenations took 289 ticks
Additional InformationThe code may take a couple of minutes to run. GetTickCount returns the number of milliseconds since Windows was started. Therefore, the output is in milliseconds. Performance improvement ranges from almost 30 times for the 1000-iteration case to almost 200 times for the 5000-iteration case. These times may vary depending on:
The product used. Your system configuration..The size of ccIncrement (larger size favors MidConcat).The number of iterations used (more iterations favors MidConcat).The size of the resultant string (larger size favors MidConcat).

How to access MAPI Address Books by using Collaboration Data Objects 1.x

Symptoms
Collaboration Data Objects (CDO) 1.1 supports programmatic access to MAPI Address Booksthrough the AddressEntries collection of an AddressList object. EachAddressList object corresponds to a MAPI Address Book and is a member ofthe AddressLists collection of the Session object.
The available AddressBooks can be enumerated by walking the AddressLists collection, and anindividual address book can be selected by indexing the AddressListscollection by name or by position.
The following sample code walks the AddressListscollection, and displays information about each address book that can be accessed. Thesecond part of the sample selects the global address list (GAL) and then walksthe Address Entries, recursively expanding Distribution Lists.
Resolution
The following sample code applies to any 32-bit Visual Basic-based product.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
Step-by-step exampleCreate a new Visual Basic project. Add a reference to the Collaboration Data Objects1.1 Object Library.Type the following code into a module.

Option ExplicitSub main()Dim objSession As MAPI.Session’ Use early binding for’ efficiency.Dim collAddressLists As AddressListsDim objAddressList As AddressListDim collAddressEntries As AddressEntriesOn Error GoTo error_olemsg’ Create a session and log on.Set objSession = CreateObject(“MAPI.Session”)’ Use a valid Exchange profile name.objSession.Logon (“<Your Profile Name Here>”)’Walk the available address books.Set collAddressLists = objSession.AddressListsFor Each objAddressList In collAddressLists’ Display collection selection indices.Debug.Print objAddressList.Name,Debug.Print objAddressList.Index,’ Display the readonly access flag.Debug.Print objAddressList.IsReadOnly,’ Display the count of recipients.Set collAddressEntries = objAddressList.AddressEntriesDebug.Print Str(collAddressEntries.Count)’ If there are any AddressEntries, display the first recipient name.If Not objAddressList.AddressEntries(1) Is Nothing Then _Debug.Print objAddressList.AddressEntries(1).NameNext objAddressList’ Walk the global address list.Set collAddressEntries = objSession.AddressLists( _”Global Address List”).AddressEntriesWalkAddressList collAddressEntries’ Close the session and log off.objSession.LogoffExit Suberror_olemsg:MsgBox “Error ” & Str(Err) & “: ” & Error$(Err)Exit SubEnd Sub’ Walk an AddressEntries collection and recursively expand’ Distribution Lists.Sub WalkAddressList(collAddressEntries As AddressEntries)Dim objaddressEntry As AddressEntryFor Each objaddressEntry In collAddressEntries’ Display the recipient’s name.Debug.Print objaddressEntry.Name,’ Display the recipient’s type.Select Case objaddressEntry.DisplayTypeCase ActMsgUserDebug.Print “Exchange Recipient”Case ActMsgDistListDebug.Print “Distribution List”WalkAddressList objaddressEntry.MembersDebug.Print “End of DL ” & objaddressEntry.NameCase ActMsgForumDebug.Print “Public Folder”Case ActMsgAgentDebug.Print “Agent”Case ActMsgPrivateDistListDebug.Print “Private DL”Case ActMsgOrganizationDebug.Print “Organization”Case ActMsgRemoteUserDebug.Print “Custom Recipient”Case ElseDebug.Print “Unknown type”End SelectNext objaddressEntryEnd SubVisual Basic only: Set Sub Main to run in the Project Properties, andthen run the application.
Other VBA applications: In the Debug/Immediate window, type MAIN,and then press ENTER.The output will appear in the Debug/Immediate window.
NotesThe address book can have restricted entries. Restricted entries will generate an”Access Denied” message:

Error -2147024891: [Collaboration Data Objects - [E_ACCESSDENIED(80070005)]]The user can include additional error handling where required.