What is the fastest way to build text?

Asked

Viewed 84 times

3

I have a large text (1000 lines) with formatting. Briefly (not this text but I will use an example) I have 2 ways to build it:

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

Or

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

at runtime and memory, which would be the most appropriate? Or the two run at the same speed?

I’m using the visual studio 2017.

  • 1

    I think if there is a difference it will be so minimal that you won’t even be able to notice! There are worse things to worry about in an application.

1 answer

3


The first undoubtedly because it in practice is the same as

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

If it’s with variables it’s the same as:

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

I put in the Github for future reference.

The second is 4 isolated operations. therefore it costs more expensive. 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 gain if you can give a size at least approximate to the string final, even if it is a little exaggerated can compensate quite.

If you’re only gonna do four appends doesn’t pay to use the StringBuilder, it serves for a large amount of inclusions and either in a loop or similar mechanism. If it is without a loop in general it pays more to use a Concat(), Join(), Format() or even interpolation.

For this specific example, if you have nothing else you should do the simplest, it will be the fastest too. If it is only that it would be too absurd to use the first one. The second one would only be absurd.

see more in:

It doesn’t matter if you’re using Visual Studio 2017, This has nothing to do with the IDE.

  • So I used a very simple example but in a system where I have 400 lines to run a query sql I could have more than 100 lines so I wanted to know even which one to use so I don’t miss any problems in performace

  • 1

    Well, when you want to ask a question the ideal thing is to ask what you want to know, to put all the details. It’s like I’m programming a computer, if I don’t put everything in it, I’ll have problems. Since we don’t know for sure what he wants to do, he has no way of knowing which one to use. That is why it is better to understand the whole mechanism to make the decision in each circumstance, since each is different from the other.

  • OK I specified a little better, so if I have a text it is much better to concatenate in 1 append only than to make 1000 appends ?

  • It’s not specified better, it’s the same thing, only now it has a number that doesn’t mean anything, I keep saying the same thing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.