Performance of Split vs. Substring and IndexOf?

J

Jonas

Hi!

If I want to get the first element of a delimited string, which of this two
methods would be the best performancevise?

Dim s0 as String = "abc;def;ggg"
Dim s1 as String
Dim s2 as String

Method 1:
s1 = s0.Split(";")(0)

Method 2:
s2 = s0.Substring(0, s0.IndexOf(";"))


Brgds

Jonas
 
A

Armin Zingler

Jonas said:
If I want to get the first element of a delimited string, which of
this two methods would be the best performancevise?

Why not test it?
Dim s0 as String = "abc;def;ggg"
Dim s1 as String
Dim s2 as String

Method 1:
s1 = s0.Split(";")(0)

Method 2:
s2 = s0.Substring(0, s0.IndexOf(";"))


I guess Method2 is faster because only the first part is extracted from the
string. You can also try to pass a char instead of a string to IndexOf:

s2 = s0.Substring(0, s0.IndexOf(";"c)) ' ";"c for char literals
 
C

Cor

Hi Armin,

I had the same answer but changed it (even with the character).

See my answer.

Cor
 
A

Armin Zingler

Cor said:
Hi Armin,

I had the same answer but changed it (even with the character).

See my answer.

What if it's executed several thousand times in a loop?
 
C

Cor

Hi Armin,

Last week I did a test about this again with the Regex in it, I don't know
if you have seen it.

The processing of the loop did take the most time.

So I think that this kind of things are only a question when it is a long
string, and then it could not be another answer than "just take the 4
characters with the substring" of course.

Cor
 
A

Armin Zingler

Cor said:
Last week I did a test about this again with the Regex in it, I don't
know if you have seen it.

No, I haven't followed the Regex threads.
The processing of the loop did take the most time.

So I think that this kind of things are only a question when it is a
long string, and then it could not be another answer than "just take
the 4 characters with the substring" of course.

You are right, but whenever I have the choice, I choose the faster version.
:)
 
E

EricJ

in addition

are you going to use the other parts of the string?
if so use the split and send it to a string array

eric
 
C

Cor

Hi Jonas,

I think you saw my answer with Armin, it is the same as he, but actualy with
strings of 256characters the difference is also almost nothing (on a modern
computer).

But I would choose for your option without the split (when it is not
something Eric said) and then with the small c from character in it as Armin
made in his example.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top