1

So I was thinking about what's more efficient, making a number by directly adding them as a string to each other, or string.Formatting them.

So I made a little code piece:

    private static void measuringStuff()
    {
        Stopwatch stw = new Stopwatch();
        Random random = new Random();
        string a;

        stw.Start();
        for (int i = 0; i < 10000000; i++)
        {
            a = random.Next(10) + "" + random.Next(10);
        }
        stw.Stop();
        Console.WriteLine("#+\"\"+#: " + stw.ElapsedMilliseconds);

        stw.Reset();
        stw.Start();
        for (int i = 0; i < 10000000; i++)
        {
            a = string.Format("{0}{1}", random.Next(10), random.Next(10));
        }
        stw.Stop();
        Console.WriteLine("string.Format: " + stw.ElapsedMilliseconds);
    }

And it turns out:

# + "" + #: 1928
string.Format: 2667

Why?

Bahadir Tasdemir
  • 10,325
  • 4
  • 49
  • 61
Squirrelkiller
  • 2,575
  • 1
  • 22
  • 41
  • 1
    Why *should* it be more effificient? – MakePeaceGreatAgain Sep 05 '16 at 13:09
  • 4
    Use whatever is more readable, that is more important than few milliseconds on a million iterations. [Related](http://stackoverflow.com/questions/296978/when-is-it-better-to-use-string-format-vs-string-concatenation) – Tim Schmelter Sep 05 '16 at 13:10
  • Because it doesn't need to make a new string for every part of the whole string. At least that's what I was taught why I should use it, besides "´# + # + stuff´ doesn't look nice" of course. – Squirrelkiller Sep 05 '16 at 13:11
  • 1
    Take a look a [this post](https://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/) about string concatenation. – Alessandro D'Andria Sep 05 '16 at 13:13
  • @Marlon: a) looks like string.Format is slower not faster and b) reading forth and back to find which param goes where does not help with readability imo. – TaW Sep 05 '16 at 13:13
  • So I love new `$"{string_interpolation}"`. – Youngjae Sep 05 '16 at 13:15
  • You've been taught wrong. `string.Format` does no tricks whatsoever to make concatenating values together faster - it's there for readability and maintainability, not performance. But in the end, it still has to do some work (e.g. parsing the format string) *plus* the `string.Concat`. It can't be *faster* than `string.Concat`. – Luaan Sep 05 '16 at 13:21
  • @YoungJae TIL about string interpolation - awesome! Just, it doesn't seem to work ony my VIsual Studio 2015, as ´a = $"{random.Next(10)}{random.Next(10)}{random.Next(10}";´ just gives me lots of errors about parenthesises and semicolons I don't have. – Squirrelkiller Sep 05 '16 at 13:24
  • @MarlonRegenhardt // It should be. See your project `Properties > Build tab, Advanced button, Language version setting` for C# 6.0 listed and `default`. Or, please see http://stackoverflow.com/a/31548221/361100 – Youngjae Sep 05 '16 at 13:37

0 Answers0