logo       

Re: Clean way to do string.join: msg#00205

org.user-groups.dotnet.padnug

Subject: Re: Clean way to do string.join


> Sounds like a great interview question!

Sounds like a great time-waster...

Okay, I had some time to kill this afternoon so I put together a
simple benchmark.

I iterated each option 1,000,000 times. I did this ten times and got
the average. Here's the results.

======================
StringBuilder result = new StringBuilder( 50 );

for( int i = 0; i < value.Length; i++ )
{
result.Append( ( result.Length > 0 && value[i].Length > 0 ? " AND
" : "" ) + value[i] );
}

return result.ToString();

1093.5 milliseconds
======================
string.Join( " AND ", CopyNonempty( value ) )

1457.8 milliseconds
======================
StringBuilder sb = new StringBuilder();
int i = 0;
for ( ; i < value.Length && value[i] == string.Empty; ++i ) ;

if ( i < value.Length )
{
sb.Append( value[ i++ ] );
for ( ; i < value.Length; ++i )
if ( value[i] != string.Empty )
sb.AppendFormat ( "{0}{1}", separator, value[i] );
}

return sb.ToString();

975.1 milliseconds
======================
StringBuilder sb = new StringBuilder();
int i = 0;
for ( ; i < value.Length && value[i] == string.Empty; ++i ) ;

if ( i < value.Length )
{
sb.Append( value[ i++ ] );
for ( ; i < value.Length; ++i )
if ( value[i] != string.Empty )
sb.Append(separator).Append(value[i]);
}

return sb.ToString();

542 milliseconds
======================

So it would appear that Stuart's solution is indeed more efficient
than my original proposal, by the margin of 118.4 milliseconds OVER
ONE MILLION EXECUTIONS! That works out to 0.0001184 milliseconds. You
can figure out the math for seconds.

This time will add up over the next few hundred years.

Granted, some applications will benefit from this type of
optimization, but my guess is that the vast majority could better
spend their time optimizing their database access or some other aspect
of the application.

Sorry, but I worked with someone at my last company who would spend
hours, if not days, trying to optimize this kind of thing, totally
ignoring much larger performance issues in the application that would
get a much bigger bang for the buck.





<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise