473,804 Members | 2,215 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What do you think of this code?

I found this code in a project:

StringBuilder sb = new StringBuilder() ;
sb.Append("SELE CT * FROM SomeTable")
.Append("WHERE SomeField = SomeValue")
.Append("ORDER BY etc etc etc")

at first I thought it was using a using statement but it's not. It works
because sb.Append returns an instance of itself. I'd be interested to hear
what everyone thinks of it.

--
Michael Culley

Nov 16 '05 #1
12 1479
Michael Culley <mc*****@NOSPAM optushome.com.a u> wrote:
I found this code in a project:

StringBuilder sb = new StringBuilder() ;
sb.Append("SELE CT * FROM SomeTable")
.Append("WHERE SomeField = SomeValue")
.Append("ORDER BY etc etc etc")

at first I thought it was using a using statement but it's not. It works
because sb.Append returns an instance of itself. I'd be interested to hear
what everyone thinks of it.


Assuming the next line uses "ToString", the developer would have been
better writing:

string x = "SELECT * FROM SomeTable "+
"WHERE SomeField=SomeV alue "+
"ORDER BY etc etc etc";

That would actually be much faster than using StringBuilder, as:

1) If the value is actually a constant, it will be very fast indeed.
Concatenated string constants are concatenated by the C# compiler,
not at runtime.
2) If it's not, it ends up as one call to String.Concat, which is able
to allocate the right amount of space to start with - the
StringBuilder version will involve at least one reallocation.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
Hi,

It's ok , the Append method return the same instance so you are not
creating a new object

Now I assume that you replace the parameter in the Append() method, if not
it has an overhead, as you don't need to use StringBuilder for that. it
would be simpler to just do:

string s= "SELECT * FROM SomeTable WHERE SomeField = SomeValue .....";
Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Michael Culley" <mc*****@NOSPAM optushome.com.a u> wrote in message
news:%2******** *******@TK2MSFT NGP14.phx.gbl.. .
I found this code in a project:

StringBuilder sb = new StringBuilder() ;
sb.Append("SELE CT * FROM SomeTable")
.Append("WHERE SomeField = SomeValue")
.Append("ORDER BY etc etc etc")

at first I thought it was using a using statement but it's not. It works
because sb.Append returns an instance of itself. I'd be interested to hear
what everyone thinks of it.

--
Michael Culley

Nov 16 '05 #3
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
[concatenation] would actually be much faster than using StringBuilder,
as:

2) ... it ends up as one call to String.Concat, which is able
to allocate the right amount of space to start with - the
StringBuilder version will involve at least one reallocation.


Although, if the StringBuilder had been constructed with a buffer larger
than the default initial size of 16 bytes in the first place, it would also
avoid allocation. I mention this because passing an initial size and/or
string to the StringBuilder ctor is perhaps one of the most often-overlooked
optimizations, at least in the code I've seen. Quite often you know about
how big the final result will be, or you at least have an idea of the
average, and it's almost always way more than 16 bytes. By default,
StringBuilder will start with 16, then jump to 32, 64, 128, etc. In the
OP's contrived example, a starting size of perhaps 512, depending on the
expected length of the SQL statement, would probably be better and would
usually keep any new allocations to zero or one rather than perhaps a half
dozen.

--Bob
Nov 16 '05 #4
Bob Grommes <bo*@bobgrommes .com> wrote:
[concatenation] would actually be much faster than using StringBuilder,
as:

2) ... it ends up as one call to String.Concat, which is able
to allocate the right amount of space to start with - the
StringBuilder version will involve at least one reallocation.


Although, if the StringBuilder had been constructed with a buffer larger
than the default initial size of 16 bytes in the first place, it would also
avoid allocation. I mention this because passing an initial size and/or
string to the StringBuilder ctor is perhaps one of the most often-overlooked
optimizations, at least in the code I've seen. Quite often you know about
how big the final result will be, or you at least have an idea of the
average, and it's almost always way more than 16 bytes. By default,
StringBuilder will start with 16, then jump to 32, 64, 128, etc. In the
OP's contrived example, a starting size of perhaps 512, depending on the
expected length of the SQL statement, would probably be better and would
usually keep any new allocations to zero or one rather than perhaps a half
dozen.


Absolutely. Still less efficient than doing it in a single set of
string concatenations (with no temporary strings involved), but better
than it currently is :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:ee******** *****@tk2msftng p13.phx.gbl...
string s= "SELECT * FROM SomeTable WHERE SomeField = SomeValue .....";


But the actual sql was much too long for one line.

--
Michael Culley
Nov 16 '05 #6
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Absolutely. Still less efficient than doing it in a single set of
string concatenations (with no temporary strings involved), but better
than it currently is :)


I don't think the efficiency is the issue in the case, generally the string
is built once, a call is made across the network and a loop is executed
retrieving records. If it was updated from the least efficient to the most
efficient method of building the string I doubt any user would notice the
speed difference even if they were looking for it. Readability is what is
important. I probably do it in the least efficient method by using sql+= on
each line to build the string.

--
Michael Culley
Nov 16 '05 #7
Michael Culley <mc*****@NOSPAM optushome.com.a u> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Absolutely. Still less efficient than doing it in a single set of
string concatenations (with no temporary strings involved), but better
than it currently is :)


I don't think the efficiency is the issue in the case, generally the string
is built once, a call is made across the network and a loop is executed
retrieving records. If it was updated from the least efficient to the most
efficient method of building the string I doubt any user would notice the
speed difference even if they were looking for it. Readability is what is
important. I probably do it in the least efficient method by using sql+= on
each line to build the string.


Why not just use a verbatim string literal then?

sql = @"
SELECT * FROM FOO
WHERE BAR
";

etc? Efficient, readable, very easy to edit... Wins all round as far as
I can see :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Thanks Jon, I didn't know you could do that. However, I'm not a big fan
because it kills your indenting, AFAIK you need to write it like this:

[STAThread]
static void Main()
{
string sql = @"SELECT *
FROM SomeTable
WHERE ID = 1";
MessageBox.Show (sql);
}

--
Michael Culley
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Michael Culley <mc*****@NOSPAM optushome.com.a u> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Absolutely. Still less efficient than doing it in a single set of
string concatenations (with no temporary strings involved), but better
than it currently is :)


I don't think the efficiency is the issue in the case, generally the string is built once, a call is made across the network and a loop is executed
retrieving records. If it was updated from the least efficient to the most efficient method of building the string I doubt any user would notice the speed difference even if they were looking for it. Readability is what is important. I probably do it in the least efficient method by using sql+= on each line to build the string.


Why not just use a verbatim string literal then?

sql = @"
SELECT * FROM FOO
WHERE BAR
";

etc? Efficient, readable, very easy to edit... Wins all round as far as
I can see :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
Michael Culley <mc*****@NOSPAM optushome.com.a u> wrote:
Thanks Jon, I didn't know you could do that. However, I'm not a big fan
because it kills your indenting, AFAIK you need to write it like this:

[STAThread]
static void Main()
{
string sql = @"SELECT *
FROM SomeTable
WHERE ID = 1";
MessageBox.Show (sql);
}


No, you can put the indenting in yourself. Of course, the whitespace
will still be in the SQL, but that shouldn't make any real difference,
should it? I'd rather have it indented nicely in the code than in the
server :)

Here's another alternative:

string sql = "SELECT * "+
"FROM SomeTable "+
"WHERE ID = 1";

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

52
6444
by: Tony Marston | last post by:
Several months ago I started a thread with the title "What is/is not considered to be good OO programming" which started a long and interesting discussion. I have condensed the arguments into a single article which can be viewed at http://www.tonymarston.net/php-mysql/good-bad-oop.html I fully expect this to be the start of another flame war, so sharpen your knives and get stuck in!
23
2823
by: darwinist | last post by:
What PHP Represents There is no shortage of complaints one could make about php as a language, and although the list does shrink with each release, some of them are inherent to the origins and development process of this, the most popular of the web-based, server-side, glue-languages. That said, most descriptions of what is good about php, fail to do it justice. Although they are generally enthusiastic and sometimes fanatical, no...
220
19198
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
92
6553
by: Reed L. O'Brien | last post by:
I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption? cheers, reed
137
7209
by: Philippe C. Martin | last post by:
I apologize in advance for launching this post but I might get enlightment somehow (PS: I am _very_ agnostic ;-). - 1) I do not consider my intelligence/education above average - 2) I am very pragmatic - 3) I usually move forward when I get the gut feeling I am correct - 4) Most likely because of 1), I usually do not manage to fully explain 3) when it comes true. - 5) I have developed for many years (>18) in many different environments,...
125
14874
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from software giant such as Microsoft SQL Server, Oracle, and Sybase? Is PostgreSQL reliable enough to be used for high-end commercial application? Thanks
121
10198
by: typingcat | last post by:
First of all, I'm an Asian and I need to input Japanese, Korean and so on. I've tried many PHP IDEs today, but almost non of them supported Unicode (UTF-8) file. I've found that the only Unicode support IDEs are DreamWeaver 8 and Zend PHP Studio. DreamWeaver provides full support for Unicode. However, DreamWeaver is a web editor rather than a PHP IDE. It only supports basic IntelliSense (or code completion) and doesn't have anything...
46
4269
by: Keith K | last post by:
Having developed with VB since 1992, I am now VERY interested in C#. I've written several applications with C# and I do enjoy the language. What C# Needs: There are a few things that I do believe MSFT should do to improve C#, however. I know that in the "Whidbey" release of VS.NET currently
13
5065
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
36
2596
by: Pat | last post by:
Hi, I've run into a strange problem, but one that seems like it might be fairly common. I have a single base class, from which several other classes are derived. To keep the example simple, the base class is "Animal" and the derived classes are "Cat," "Dog," and "Horse." The base class has a pure virtual method:
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10351
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10096
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.