Results 1 to 17 of 17

Thread: String.Concat and String.Copy

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jan 2007
    Posts
    17

    String.Concat and String.Copy

    I found this online:

    Code:
    'The following source code concatenate two strings.
    
    Dim str1 As String = "ppp"
    Dim str2 As String = "ccc"
    Dim strRes As String = String.Concat(str1, str2)
    Console.WriteLine(strRes)
    
    'The following source code concatenates one string and one object.
    
    Dim obj As Object = 12
    strRes = String.Concat(str1, obj)
    Console.WriteLine(strRes)
    
    'The Copy method copies contents of a string to another. The Copy method takes a string as input and returns another string with the same contents as the input string. For example, the following code copies str1 to strRes.
    
    strRes = String.Copy(str1)
    Console.WriteLine("Copy result :" + strRes)
    My question is, what is the advantage of using concatenate and copy over something like this:

    Code:
    'concatenate
    Console.WriteLine(str1 + str2)
    
    'copy
    strRes = str1
    Console.WriteLine(strRes)
    Thanks.

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: String.Concat and String.Copy

    In this case.... nothing. Just another way to skin a cat. (no pun intended).

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: String.Concat and String.Copy

    The advantage of String.Concat becomes apparent when concatenating multiple strings. It will concatenate them efficiently, while just using the concatenation operator will create intermediate String objects that use extra memory unnecessarily. For example, this:
    vb.net Code:
    1. Dim str As String = "str1" & "str2" & "str3" & "str4"
    will actually create three new String objects, two of which are simply discarded and occupy memory unnecessarily. This:
    vb.net Code:
    1. Dim str As String = String.Concat("str1", "str2", "str3", "str4")
    will only create one new String object that gets populated efficiently using pointers in C# unsafe code. Remember, the Framework is written almost entirely in C#.


    The difference between String.Copy and a straight assignment is the Copy actually creates a new String object with the same contents, rather than both variables referring to the same String object with an assignment. In most cases that won't actually matter but it may do in some. To see what I mean, try this:
    Code:
    Dim str1 As String = "Hello World"
    Dim str2 As String = str1
    Dim str3 As String = "Goodbye Cruel World"
    Dim str4 As String = String.Copy(str3)
    
    MessageBox.Show((str1 Is str2).ToString(), "str1 Is str2")
    MessageBox.Show((str3 Is str4).ToString(), "str3 Is str4")
    That shows that str1 and str2 both refer to the same String object, while str3 and str4 refer to two different String objects.
    Last edited by jmcilhinney; Jan 3rd, 2009 at 02:00 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: String.Concat and String.Copy

    So what's the advantage of that over StringBuilder? I was always taught to use StringBuilder when concatenating multiple string items together.... I didn't realize that Concat worked in a similar manner. Have I been misinformed all these years?

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: String.Concat and String.Copy

    Quote Originally Posted by techgnome
    So what's the advantage of that over StringBuilder? I was always taught to use StringBuilder when concatenating multiple string items together.... I didn't realize that Concat worked in a similar manner. Have I been misinformed all these years?

    -tg
    No, not misinformed. String.Concat is a single method call, while with a StringBuilder you can call Append multiple times and still have the string built efficiently. If you want to build a string from several substrings and you know all the substrings to begin with then you should use String.Concat. By knowing all the substrings to begin with I mean that you can access each one using a simple expression.

    If the substrings are not all known at the same time then a StringBuilder is a better option because you can call Append multiple times over many lines of code. That's useful if you need to use If statements to decide which substrings to use, for instance.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  6. #6
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: String.Concat and String.Copy

    Ah, OK.... makes sense. Usually when I'm using stringBuilder it's doing mutiple lines over time.

    Thanks
    -tg

    ps - I owe you some rep for that.
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Jan 2007
    Posts
    17

    Re: String.Concat and String.Copy

    Thanks a lot for that help.

    Quote Originally Posted by jmcilhinney
    It will concatenate them efficiently, while just using the concatenation operator will create intermediate String objects that use extra memory unnecessarily.
    Why only three? I don't follow... in your example you presented 5 strings.

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: String.Concat and String.Copy

    I only count four strings in his example, in which case, three would be correct, as the number of intermediaries would be equal to the number of concatenation operators.
    My usual boring signature: Nothing

  9. #9
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: String.Concat and String.Copy

    it will create three NEW strings....
    The first one is string1 & string2 .... the second one will be the previously created string (call it string1string2) with string3 added (string1string2string3) .... at this point string1string2 is then discarded..... then it concatenates string4 onto that resulting string1string2string3string4 .... and discarding string1string2string3 ....

    See, the problem is that strings are immutable, meaning once set, they cannot change... so when you make changes, be it concatenation or replacing and existing character with another, or even deleting a character from the string, it actually has to create a new memory space to store the new value, and returns that.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Jan 2007
    Posts
    17

    Re: String.Concat and String.Copy

    Quote Originally Posted by techgnome
    it will create three NEW strings....
    The first one is string1 & string2 .... the second one will be the previously created string (call it string1string2) with string3 added (string1string2string3) .... at this point string1string2 is then discarded..... then it concatenates string4 onto that resulting string1string2string3string4 .... and discarding string1string2string3 ....

    See, the problem is that strings are immutable, meaning once set, they cannot change... so when you make changes, be it concatenation or replacing and existing character with another, or even deleting a character from the string, it actually has to create a new memory space to store the new value, and returns that.

    -tg
    Makes sense, though in the end onlyone string is kept: string1string2string3string4. Am I right? When jmcilhinney first said that 3 new strings are created it makes it sound like quite a bit of memory is being used up, when in actuality that memory is immediately made available again.
    Last edited by razzendahcuben; Jan 5th, 2009 at 11:27 AM.

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: String.Concat and String.Copy

    Quote Originally Posted by razzendahcuben
    Makes sense, though in the end onlyone string is kept: string1string2string3string4. Am I right? When jmcilhinney first said that 3 new strings are created it makes it sound like quite a bit of memory is being used up, when in actuality that memory is immediately made available again.
    Yes, the memory is available again but it does have to be reclaimed, which takes time. The real issue is the fact that copying data from string to string to string is slow. Try this code to see how a lot of string concatenation can slow down execution of your app:
    Code:
    Imports System.Text
    
    Module Module1
    
        Sub Main()
            Dim substring As String = "Hello World"
            Dim str As String = String.Empty
            Dim timer As Stopwatch = Stopwatch.StartNew()
    
            For count As Integer = 1 To 1000
                str &= substring
            Next
    
            Console.WriteLine(timer.Elapsed.ToString())
    
            Dim substrings(1000 - 1) As String
    
            For index As Integer = 0 To substrings.GetUpperBound(0)
                substrings(index) = substring
            Next
    
            timer = Stopwatch.StartNew()
    
            str = String.Concat(substrings)
    
            Console.WriteLine(timer.Elapsed.ToString())
    
            Dim builder As New StringBuilder
    
            timer = Stopwatch.StartNew()
    
            For count As Integer = 1 To 1000
                builder.Append(substring)
            Next
    
            Console.WriteLine(timer.Elapsed.ToString())
            Console.ReadLine()
        End Sub
    
    End Module
    Now, admittedly, all three of those operations happen pretty quickly but using the & operator is over 100 times slower than using the StringBuilder and over 200 times slower than String.Concat. Even if we include the creation of the array in the time for String.Concat like this:
    Code:
    Imports System.Text
    
    Module Module1
    
        Sub Main()
            Dim substring As String = "Hello World"
            Dim str As String = String.Empty
            Dim timer As Stopwatch = Stopwatch.StartNew()
    
            For count As Integer = 1 To 1000
                str &= substring
            Next
    
            Console.WriteLine(timer.Elapsed.ToString())
    
            timer = Stopwatch.StartNew()
    
            Dim substrings(1000 - 1) As String
    
            For index As Integer = 0 To substrings.GetUpperBound(0)
                substrings(index) = substring
            Next
    
            str = String.Concat(substrings)
    
            Console.WriteLine(timer.Elapsed.ToString())
    
            Dim builder As New StringBuilder
    
            timer = Stopwatch.StartNew()
    
            For count As Integer = 1 To 1000
                builder.Append(substring)
            Next
    
            Console.WriteLine(timer.Elapsed.ToString())
            Console.ReadLine()
        End Sub
    
    End Module
    it is still the fastest of the three methods.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Junior Member
    Join Date
    Jan 2007
    Posts
    17

    Re: String.Concat and String.Copy

    Thanks for that code, that's very helpful.

  13. #13
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: String.Concat and String.Copy

    No, no, no.

    I've spent days looking over this in detail in the past. And days arguing over this. Look at ILDASM for this.

    When joining multiple hardcoded strings, using the & is better.

    Dim str As String = "str1" & "str2" & "str3" & "str4"

    The strings are joined at compile time. No copying.

    When joining multiple variable strings, then & is the same as string.concat.

    str1 = str2 & str3 & str4
    str1 = String.Concat(str2,str3,str4)

    They both evaluate to string.concat.

    When building a string in a loop, the StringBuilder then becomes handy.


    str2 & str3 & str4 will not create multiple copies of strings.

    But &= will create string copies.

  14. #14
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: String.Concat and String.Copy

    Quote Originally Posted by mendhak
    No, no, no.

    I've spent days looking over this in detail in the past. And days arguing over this. Look at ILDASM for this.

    When joining multiple hardcoded strings, using the & is better.

    Dim str As String = "str1" & "str2" & "str3" & "str4"

    The strings are joined at compile time. No copying.
    You'd never join two string literals together anyway though. That was just an over-simplified example.
    Quote Originally Posted by mendhak
    When joining multiple variable strings, then & is the same as string.concat.

    str1 = str2 & str3 & str4
    str1 = String.Concat(str2,str3,str4)

    They both evaluate to string.concat.
    That I wasn't aware of, but it certainly does make sense.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  15. #15
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: String.Concat and String.Copy

    I know it's a simplified example but I often see it in blogs as substitutes. I think that's what leads to the entire string concatenation confusion. I often call it the 'string concatefusion' but that phrase hasn't amused anyone yet. (Hint)

  16. #16
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: String.Concat and String.Copy

    Quote Originally Posted by mendhak
    I often call it the 'string concatefusion' but that phrase hasn't amused anyone yet. (Hint)
    Consistency is good... usually.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  17. #17
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: String.Concat and String.Copy

    I think I could speculate at length as to why that phrase hasn't amused anyone. It really is worth some speculation, as it suggests something about how the brain processes syllables, but that would be too wildly off topic, though I hope to start a thread on some learning issues one of these months.

    I'm surprised that the compiler is sharp enough to swap in concat to improve efficiency, but I think that when I ran a test between stringbuilder and the & operator, I used a couple &= lines, rather than a multiple & line, so I was testing only one case, and would have seen something different had I tested differently. However, I'm currently feeling too mellow and lethargic to go back and see what difference it makes in real time. It has been a very energetic day, and I'm currently about as relaxed as I can be while still remaining awake. It was a nice thing to note, though.
    My usual boring signature: Nothing

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