views:

56

answers:

4

What should be the best way to write code:

1)

Dim current = Request.Path
current = current.Remove(0, 1)
current = current.Replace(".aspx", "")

2)

Dim current = Request.Path.Remove(0, 1).Replace(".aspx", "")

3)

Dim current = Request.Path
Dim current2 = current.Remove(0, 1)
Dim current3 = current.Replace(".aspx", "")

Or 1-2 make no difference?

A: 

Strings are immutable in .Net so you will get the same performance out of all of those methods.

Josh
+1  A: 

Those are all the same. Try

Path.GetFileNameWithoutExtension(Request.Path)
Paul Alexander
+1  A: 

All three are basically the same.

Remember strings are immutable. Every time you call a method on a string, it allocates a new string object, so calling Remove() creates a new object, which is then used to call Replace().

1 & 2 are basically identical. #3 is a little different because you use 3 separate variables, so you're holding on to the references to those strings so they can be used later. The garbage collector should know what to do with all 3 examples and handle them roughly the same however, whether you store the intermediate strings as variables or not.

I would use #2, simply because it's fewer lines of code and doesn't sacrafice readability but it's still a fairly short bit of code.

Dan Herbert
+1  A: 

Those calls can throw exceptions. For toy code it's okay not to check but, after you get the path, you should check against String.NullOrEmpty and the length before you call Remove. So, that's why I would avoid #2. Other than that, #1 seems cleaner unless you need to use the intermediate values (current as the path and current2) somewhere else in the method.

JP Alioto
u got a point man
Shimmy