Reputation: 1054
I have recently noticed on my performance assist tool I use on Visual Studio 2013 any time I make a complex string
as a sample string:
"SELECT * from calls where randid = '" & randid & "'"
it will instead recommend using string format
String.Format("SELECT * from calls where randid = '{0}'", randid)
same with using value initializers instead of
Dim cb As New MySqlConnectionStringBuilder
cb.Database = dbfile
cb.Server = dbserver
cb.UserID = dbuser
cb.Password = dbpassw
use
Dim cb As New MySqlConnectionStringBuilder() With {.Database = dbfile, .Server = dbserver, .UserID = dbuser, .Password = dbpassw}
Do these formats actually improve the performance of an application or is it recommending these for aesthetics?
Upvotes: 1
Views: 99
Reputation: 216348
Out of curiosity (I am absolutely sure that mini-optimizations are devilish) I have tested the difference with this code using LinqPad:
Sub Main
Dim test = "999"
Dim sw = new Stopwatch()
sw.Start()
for i = 0 to 100000
Dim s = "SELECT * FROM TABLE WHERE FIELD = '" + test + "'"
Next
sw.Stop()
sw.Elapsed.Dump("Concat")
sw = new Stopwatch()
sw.Start()
for i = 0 to 100000
Dim s = string.Format("SELECT * FROM TABLE WHERE FIELD = '{0}'", test)
Next
sw.Stop()
sw.Elapsed.Dump("Format")
End Sub
with these results:
Concat
00:00:00.0101903
Format
00:00:00.0365234
The output changes noticeably if we use an integer for the test variable because now the concatenation should use ToString()
Dim test = 999
Concat
00:00:00.0198107
Format
00:00:00.0485193
So, for whatever reason your tool suggest to use the string.Format approach it is not to get better performance.
Upvotes: 1
Reputation: 125650
In the first one compiler will generate String.Concat
method call for your string concatenation:
return "test" + value + "test";
it translated into
IL_0000: ldstr "test"
IL_0005: ldarg.0
IL_0006: box [mscorlib]System.Int32
IL_000b: ldstr "test"
IL_0010: call string [mscorlib]System.String::Concat(object, object, object)
IL_0015: ret
Both String.Concat
and String.Format
will cause boxing (I assumed randid
is an int
). You should call ToString()
on it anyway to make it better.
The second one is a lay. Compiler will generate properties assignments anyway, so
Dim cb As New MySqlConnectionStringBuilder() With {.Database = dbfile, .Server = dbserver, .UserID = dbuser, .Password = dbpassw}
is transformed into
Dim cb As New MySqlConnectionStringBuilder
cb.Database = dbfile
cb.Server = dbserver
cb.UserID = dbuser
cb.Password = dbpassw
by compiler.
Upvotes: 1