Text construction, performance question

2

I have a question regarding text construction performance, I have a large text (1000 lines) with formatting etc, in a summarized way (it's not this text but I'll use an example) I have 2 ways to construct it

StringBuilder sb = new StringBuilder();
    sb.append("oi" +
    "meu nome" +
    "é" +
    "Jonny");

Or

    sb.append("oi");
    sb.append("meu nome");
    sb.append("é");
    sb.append("Jonny");

In terms of execution time and memory, what would be the most appropriate? or are the two running at the same speed? (I'm using visual studio 2017)

    
asked by anonymous 23.02.2018 / 15:53

1 answer

2

The first one without a doubt because in practice it is the same as

sb.append("oimeu nomeéJonny");

If it is with variables it is the same as:

sb.append(string.Concat(v1, v2, v3, v4));

The second is 4 isolated operations. therefore it costs more. Of course there will be gain in a large operation, but the gain will be greater if you can avoid some of these operations. There will be a gain if you can give a size at least approximate to the final string , even if it is a bit overdone it can compensate a lot.

If you are only doing 4 appends it does not pay to use StringBuilder ", it serves a large amount of inclusions and is in a loop or similar mechanism. If it is without a loop it generally pays more to use a Concat() , Join() , Format() or even interpolation .

For this specific example, if you do not have anything else you should do the simplest, it will be the fastest too. If that's all it would be a great nonsense to use the first one. The second would be just absurd.

see more at:

It does not matter if you're using Visual Studio 2017, this has nothing to do with IDE .

    
23.02.2018 / 16:00