Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

hi all,

 

Got a little question about Substring (yes, its a .net 2.0 application i'm using it in)

 

if you use the following code on MyString that is less then 30 characters long, i get an error: (ArgumentOutOfRangeException) :(

MyString.Substring(0, 30)

I got 2 solutions:

Solution 1:

If MyString.Length < 30 Then
   Myfield = MyString
Else
   Myfield = MyString.SubString(0,30)
End If

Solution 2:

MyField = MyString.PadRight(30).Substring(0, 30)

 

What is the best solution?

Or is there a method that can take everything if it is less then 30 and only the 30 first chars if it is longer than 30 chars?

Edited by Vampie
Posted
I would use Solution 1, since it involves a check and then action based on that check. I'd avoid padding a string just to use substring on it since string operations are generally "slow" compaired to a check on (int < int).

~Nate�

___________________________________________

Please use the [vb]/[cs] tags on posted code.

Please post solutions you find somewhere else.

Follow me on Twitter here.

  • Leaders
Posted
Unless you are doing at least thousands upon thousands of string comparisions, there really is no legitimate concern about performance. It is good to know which method is faster, but the real reason that I would go with option # 1 is because it is more straight-forward and self-explanitory, even if it is longer. In this particular instance, I think either solution would be perfectly adequate, but in terms of general coding style it is best to avoid the potentially cryptic and stick with code that spells out what it is doing.
[sIGPIC]e[/sIGPIC]
Posted

I think that marble has a valid point about clarity and in general I agree with him that the performance gain is negligible; however, all the applications which make this assumption in a few places burn extra CPU cycles for no reason. Over several applications and an OS this can lead to a noticable slow down.

 

IMHO

~Nate�

___________________________________________

Please use the [vb]/[cs] tags on posted code.

Please post solutions you find somewhere else.

Follow me on Twitter here.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...