Vampie Posted November 3, 2008 Posted November 3, 2008 (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 November 3, 2008 by Vampie Quote
Nate Bross Posted November 3, 2008 Posted November 3, 2008 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). Quote ~Nate� ___________________________________________ Please use the [vb]/[cs] tags on posted code. Please post solutions you find somewhere else. Follow me on Twitter here.
TaleOfTimes Posted November 3, 2008 Posted November 3, 2008 The one with the conditionally will be hugely faster Quote
Vampie Posted November 3, 2008 Author Posted November 3, 2008 thank you both. :-) Conditionally it will be then. Quote
Leaders snarfblam Posted November 6, 2008 Leaders Posted November 6, 2008 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. Quote [sIGPIC]e[/sIGPIC]
Nate Bross Posted November 7, 2008 Posted November 7, 2008 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 Quote ~Nate� ___________________________________________ Please use the [vb]/[cs] tags on posted code. Please post solutions you find somewhere else. Follow me on Twitter here.
Vampie Posted November 7, 2008 Author Posted November 7, 2008 HI, Wise words have been spoken here. Agood lesson learned :-) Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.