Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Insert variable into string

Insert variable into string

Scheduled Pinned Locked Moved C#
question
12 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Offline
    L Offline
    lukeer
    wrote on last edited by
    #1

    Hello experts, which advantages does one of these two methods

    return (string.Format("Device #{0}", devNr));
    return ("Device #" + devNr.ToString());

    have over the other one? They seem to produce identical results.

    Ciao, luker

    L Y 2 Replies Last reply
    0
    • L lukeer

      Hello experts, which advantages does one of these two methods

      return (string.Format("Device #{0}", devNr));
      return ("Device #" + devNr.ToString());

      have over the other one? They seem to produce identical results.

      Ciao, luker

      L Offline
      L Offline
      Lukasz Nowakowski
      wrote on last edited by
      #2

      They produce identical results. The first one is consider better because it uses less memory. The second version allocates memory for 3 strings ("Device #", result of devNr.ToString() and result of entire statement), which makes application consume more memory. The first one isn't (to my knowledge) creating such an overhead. If you need to use second form it's better to use StringBuilder class. And personally I consider first form more readable.

      R K K W 4 Replies Last reply
      0
      • L Lukasz Nowakowski

        They produce identical results. The first one is consider better because it uses less memory. The second version allocates memory for 3 strings ("Device #", result of devNr.ToString() and result of entire statement), which makes application consume more memory. The first one isn't (to my knowledge) creating such an overhead. If you need to use second form it's better to use StringBuilder class. And personally I consider first form more readable.

        R Offline
        R Offline
        Rhys Jacob
        wrote on last edited by
        #3

        lukasz_nowakowski wrote:

        And personally I consider first form more readable.

        I agree, String.Format is more readable, especially when you have a few more arguments.

        1 Reply Last reply
        0
        • L Lukasz Nowakowski

          They produce identical results. The first one is consider better because it uses less memory. The second version allocates memory for 3 strings ("Device #", result of devNr.ToString() and result of entire statement), which makes application consume more memory. The first one isn't (to my knowledge) creating such an overhead. If you need to use second form it's better to use StringBuilder class. And personally I consider first form more readable.

          K Offline
          K Offline
          Keith Barrow
          wrote on last edited by
          #4

          I totally agree the 1st form is better, just on readability alone. I'd question your point about the StringBuilder as a replacement for the second form, creating an instance of this type has some overhead, for small concatenations the string builder is worse than the code supplied in the OP, but it has become received wisdom that StringBuilder is more efficient. I posted a link a while back http://www.yoda.arachsys.com/csharp/stringbuilder.html[^] to an archive of stuff John Skeet has written about c# amongst others. He has tested the received wisdom, and found it wanting, the section "So I Should Use StringBuilder Everywhere, Right?" is really the nub of the problem. It's worth doing the test he suggests, for "small" concats the overhead of the StringBuilder outweighs the benefits (and dirties the code). For multiple concats (e.g. in a loop) StringBuilder `is _much_ more efficient. **Dalek Dave:** There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter. **Pete o'Hanlon:** If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.`

          W 1 Reply Last reply
          0
          • L Lukasz Nowakowski

            They produce identical results. The first one is consider better because it uses less memory. The second version allocates memory for 3 strings ("Device #", result of devNr.ToString() and result of entire statement), which makes application consume more memory. The first one isn't (to my knowledge) creating such an overhead. If you need to use second form it's better to use StringBuilder class. And personally I consider first form more readable.

            K Offline
            K Offline
            kevinnicol
            wrote on last edited by
            #5

            Not to mention that the first form makes localization easier between english and any of {French, Spanish, Italian, etc..}

            P 1 Reply Last reply
            0
            • L Lukasz Nowakowski

              They produce identical results. The first one is consider better because it uses less memory. The second version allocates memory for 3 strings ("Device #", result of devNr.ToString() and result of entire statement), which makes application consume more memory. The first one isn't (to my knowledge) creating such an overhead. If you need to use second form it's better to use StringBuilder class. And personally I consider first form more readable.

              W Offline
              W Offline
              William Winner
              wrote on last edited by
              #6

              I'm just curious about something here. The header for String.Format looks like:

              string Format(string strInput, object objInput)

              right? So, right away, a new string is created, along with a reference to the object. Now, the code, would have to first find the starting and ending brace and pull out the formatting codes. Then, it would have to take the object and apply the formatting code to it and then return the part of the string before the brace, the formatted code, and the part of the string after the brace. In other words, if you had passed it "format {0} me", the return would look like:

              return left(strInput, startingBraceIndex) & Format(objInput, formatCode) & right(strInput, strInput.Length - endingBraceIndex - 1)

              or something like that. Of course, it is (hopefully) optimized a bit, so that it's not creating as many copies, but still, wouldn't more memory have to be used for the Format method, plus more processing cycles because or what all has to be done...whereas the second routine is much more straightforward. As far as performance, I just don't see how the first is more efficient than the second. I also don't see how the first is more readable...even with more parameters, you would have to know what was in each spot in the array, so as far as readability, the second would be more readable as well. Is

              object[] objArray = {devNr, idNr, testNr};
              return string.Format("Device #{0}, ID#{1}, Test#{2}", objArry);

              really more readable than:

              return "Device #" + devNr + ", ID#" + idNr + ", Test#" + testNr

              ? Sure the first one is a bit cleaner, but IMO, it's not more readable. Besides, whatever happened to Occam's Razor?

              L 1 Reply Last reply
              0
              • W William Winner

                I'm just curious about something here. The header for String.Format looks like:

                string Format(string strInput, object objInput)

                right? So, right away, a new string is created, along with a reference to the object. Now, the code, would have to first find the starting and ending brace and pull out the formatting codes. Then, it would have to take the object and apply the formatting code to it and then return the part of the string before the brace, the formatted code, and the part of the string after the brace. In other words, if you had passed it "format {0} me", the return would look like:

                return left(strInput, startingBraceIndex) & Format(objInput, formatCode) & right(strInput, strInput.Length - endingBraceIndex - 1)

                or something like that. Of course, it is (hopefully) optimized a bit, so that it's not creating as many copies, but still, wouldn't more memory have to be used for the Format method, plus more processing cycles because or what all has to be done...whereas the second routine is much more straightforward. As far as performance, I just don't see how the first is more efficient than the second. I also don't see how the first is more readable...even with more parameters, you would have to know what was in each spot in the array, so as far as readability, the second would be more readable as well. Is

                object[] objArray = {devNr, idNr, testNr};
                return string.Format("Device #{0}, ID#{1}, Test#{2}", objArry);

                really more readable than:

                return "Device #" + devNr + ", ID#" + idNr + ", Test#" + testNr

                ? Sure the first one is a bit cleaner, but IMO, it's not more readable. Besides, whatever happened to Occam's Razor?

                L Offline
                L Offline
                Lukasz Nowakowski
                wrote on last edited by
                #7

                Interesting point... I was curious, so I checked String.Format with .NET Reflector... Actually it doesn't split string. Under the hood it uses StringBuilder.AppendFormat. Method is quite long and operates on char[] (from format.ToCharArray()). And I'm tired, so didn't trace the method body. Just took a look on it.

                1 Reply Last reply
                0
                • K Keith Barrow

                  I totally agree the 1st form is better, just on readability alone. I'd question your point about the StringBuilder as a replacement for the second form, creating an instance of this type has some overhead, for small concatenations the string builder is worse than the code supplied in the OP, but it has become received wisdom that StringBuilder is more efficient. I posted a link a while back http://www.yoda.arachsys.com/csharp/stringbuilder.html[^] to an archive of stuff John Skeet has written about c# amongst others. He has tested the received wisdom, and found it wanting, the section "So I Should Use StringBuilder Everywhere, Right?" is really the nub of the problem. It's worth doing the test he suggests, for "small" concats the overhead of the StringBuilder outweighs the benefits (and dirties the code). For multiple concats (e.g. in a loop) StringBuilder `is _much_ more efficient. **Dalek Dave:** There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter. **Pete o'Hanlon:** If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.`

                  W Offline
                  W Offline
                  William Winner
                  wrote on last edited by
                  #8

                  Interestingly, the String.Format uses a StringBuilder...

                  K 1 Reply Last reply
                  0
                  • W William Winner

                    Interestingly, the String.Format uses a StringBuilder...

                    K Offline
                    K Offline
                    Keith Barrow
                    wrote on last edited by
                    #9

                    I'm not convinced String.Format is more efficient than the straight concat, but I do think the format route is clearer. Disassembling String.Format gives this line:

                    StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));

                    So it is likely that, as long as the argument passed average 8 characters or less, the StringBuilder will probably be more efficient at first glance. Of course, I haven't tested this, but it would be easy to rig a test to find out. The point I was trying to make was that the assumption that StringBuilder is always more efficient than direct string manipulation is demonstrably false. Additionally, I'd say, unless the code is a block you know will be heavily repeated, early optimisation will ruin otherwise clear code without real benefit. I personally would only consider using a StringBuilder when I know this is the case, or testing reveals poor performance, or the system must perform with the highest possible efficiency for some reason(e.g. real time). This is in line with the KSS and YAGNI principles.

                    Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter. Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                    W 1 Reply Last reply
                    0
                    • K Keith Barrow

                      I'm not convinced String.Format is more efficient than the straight concat, but I do think the format route is clearer. Disassembling String.Format gives this line:

                      StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));

                      So it is likely that, as long as the argument passed average 8 characters or less, the StringBuilder will probably be more efficient at first glance. Of course, I haven't tested this, but it would be easy to rig a test to find out. The point I was trying to make was that the assumption that StringBuilder is always more efficient than direct string manipulation is demonstrably false. Additionally, I'd say, unless the code is a block you know will be heavily repeated, early optimisation will ruin otherwise clear code without real benefit. I personally would only consider using a StringBuilder when I know this is the case, or testing reveals poor performance, or the system must perform with the highest possible efficiency for some reason(e.g. real time). This is in line with the KSS and YAGNI principles.

                      Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter. Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                      W Offline
                      W Offline
                      William Winner
                      wrote on last edited by
                      #10

                      I wasn't arguing for StringBuilder. I was just noting that you were saying for smaller concats, StringBuilder won't be more efficient. You were saying you preferred format 1 (albeit for readability) and I was just pointing out that format 1 used a StringBuilder which you were seeming to argue against. I was just pointing out the irony is all. For what he wrote, I would always lean towards the second format. Especially now that I've seen the path String.Format(String, Object) takes: String.Format(String, Object) calls String.Format(IFormatProvider, String, Object[]) calls StringBuilder(int capacity) and StringBuilder.AppendFormat(IFormatProvider, string format, params object[] args) and StringBuilder.ToString() which calls string.FastAllocateString(int length) then concatenates each of the StringBuilder parts. It's way more code being run.

                      1 Reply Last reply
                      0
                      • K kevinnicol

                        Not to mention that the first form makes localization easier between english and any of {French, Spanish, Italian, etc..}

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #11

                        Yes, I was going to make that point too.

                        1 Reply Last reply
                        0
                        • L lukeer

                          Hello experts, which advantages does one of these two methods

                          return (string.Format("Device #{0}", devNr));
                          return ("Device #" + devNr.ToString());

                          have over the other one? They seem to produce identical results.

                          Ciao, luker

                          Y Offline
                          Y Offline
                          yu jian
                          wrote on last edited by
                          #12

                          The first one

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups