A
A
Alexey Lebedev2014-09-17 17:09:23
C++ / C#
Alexey Lebedev, 2014-09-17 17:09:23

C#. What is the optimal way to remove newlines?

There is a line about 20MB.
It has a lot of line breaks.
I'm thinking about 2 options.
one)

int pos=result.IndexOf("\n");
              result=result.Remove(pos, 1);

Of course it's all in cycles.
2) result=result.Replace("\n", "");
I tried on small files, still not fast.
Which is better? Are there even better options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aush, 2014-09-17
@swanrnd

@lam0x86 is right, string operations are quite optimized in .net and in very rare cases you might need some extra optimization. I checked and result = result.Replace("\n", "") works faster than the options presented.
In fact, Replace is marked with the [MethodImpl(MethodImplOptions.InternalCall)] attribute, i.e. it is optimized at the CLR level, so you can hardly make it faster without some specific optimization for your task and unsafe code.
The StringBuilder option from the comment works, except for specific cases, ~3 times slower than Replace, so don't bother.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question