Is Left right ?

Posted Wed, Jun 2 2004 3:51 by bill

Yag posted to Paul’s blog, saying that in some situations Left$ can be better than String.Substring.  I think he’s been hanging out with those marketing folk.. oops I mean media folk too much.  Of course Yag is right, Left is faster is *some* situations. First, for Left to be faster, the Microsoft.VisualBasic.dll must already have been loaded.  There’s a good chance it will have been, but not a given.  But most importantly, Left(SomeString, n) is faster only when n is 0 or n is >= SomeString.Length.  That is, when the result is either String.Empty or the entire original string.

So, IOW, Microsoft.VisualBasic.Left is faster than String.SubString when Left is not actually returning a sub-string ;-)

Filed under:

Comments

# re: If Left right ?

Wednesday, June 02, 2004 9:29 AM by bill

OK, I shoulda used CInt() - would that have made you happier? <g>

I'll have to smack Paul for unleashing you on the world... ;)

Welcome!

yag

# re: If Left right ?

Wednesday, June 02, 2004 12:04 PM by bill

Hey, thanks Yag. Yeh, Cint, or Val or CStr etc are all good examples of how VB's intrinsic methods are *usually* faster, as well as being way more functional. Left was, a bit "left" field ;-)

# re: Is Left right ?

Sunday, June 06, 2004 3:35 AM by bill

The Visual Basic.NET Internals article (published on the MSDN web site) referenced by Paul in his blog says this about Left:

<snip>

The Mid, Left, and Right methods in Visual Basic .NET all call String.Substring. However, the Visual Basic Runtime methods are optimized to prevent string allocation for some common cases. For example, the following simple case is 85 percent faster using the Visual Basic Runtime methods versus the System methods:

Dim s1, s2 As String
s2 = "abc"

' fast, prevents string allocation
s1 = Left(s2, 3)
' SubString is not optimized for this case
s1 = s2.SubString(0, 3)
<snip>

The article's example Left code is faster than the Substring code only becuase it is a situation where n = SomeString.Length. Common use would be to use Left to return n characters of a string that is n= characters long. IMO the article gives impractical advice.

I tested the code as I found it in the article, through 10 million loops and Left way out performed Substring. After John Spano at VBCity checked the code behind the Left syntax he found the same thing you report. I set s2 to 'abcdefg' and ran the test again. Substring beat the heck out of Left.

I hope not to many people have used the advice about Left in a performance critical scenario in a VB.NET program.