Results 1 to 2 of 2

Thread: Optimizing VB.NRT code with Stringbuilder

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2019
    Posts
    9

    Optimizing VB.NRT code with Stringbuilder

    I have been reading several internet articles recommending the use of Stringbuilder to concatenate strings. My question is....are there a minimum number of items being concatenated into a string before there is a noticeable improvement in processing speed.
    Fundamentally I tend to only concat about a half dozen or less items into a string. Is it worth using a Stringbuilder or is the old VB technique using "&" good enough?

    Any opinions welcomed.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: Optimizing VB.NRT code with Stringbuilder

    There is an overhead associated with a StringBuilder so it actually requires about a dozen substrings before using one is advantageous with regards to performance. Even if you are using more than that, if it's all in once place then you still shouldn't use a StringBuilder. A StringBuilder should generally be used if you are adding text, then doing some processing, then adding some text, then doing some processing, etc. If you are building text from a database table and processing one record at a time, that's an example of when to use a StringBuilder. If you just have a bunch of substrings that you want to combine then here are my recommendations:

    1. If there are two substrings, just use the concatenation operator (&).
    2. If there are three or more substrings, use the most appropriate option among the following: string interpolation, String.Format, String.Concat and String.Join or the like.

    For example, string interpolation:
    vb.net Code:
    1. Dim message1 = $"Hello, my name is {name} and I am {age} years old."
    2. Dim message2 = String.Format("Hello, my name is {0} and I am {1} years old.", name, age)
    3. Dim message3 = String.Concat(substring1, substring2, substring3)
    4. Dim message4 = String.Join(", ", item1, item2, item3)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width