Search Results

Search found 577 results on 24 pages for 'stringbuilder'.

Page 2/24 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • String assembly by StringBuilder vs StringWriter and PrintWriter

    - by CPerkins
    I recently encountered an idiom I haven't seen before: string assembly by StringWriter and PrintWriter. I mean, I know how to use them, but I've always used StringBuilder. Is there a concrete reason for preferring one over the other? The StringBuilder method seems much more natural to me, but is it just style? I've looked at several questions here (including this one which comes closest: http://stackoverflow.com/questions/602279/stringwriter-or-stringbuilder ), but none in which the answers actually address the question of whether there's a reason to prefer one over the other for simple string assembly. This is the idiom I've seen and used many many times: string assembly by StringBuilder: public static String newline = System.getProperty("line.separator"); public String viaStringBuilder () { StringBuilder builder = new StringBuilder(); builder.append("first thing" + newline); builder.append("second thing" + newline); // ... several things builder.append("last thing" + newline); return builder.toString(); } And this is the new idiom: string assembly by StringWriter and PrintWriter: public String viaWriters() { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.println("first thing"); printWriter.println("second thing"); // ... several things printWriter.println("last thing"); printWriter.flush(); printWriter.close(); return stringWriter.toString(); }

    Read the article

  • Is there something better than a StringBuilder for big blocks of SQL in the code

    - by Eduardo Molteni
    I'm just tired of making a big SQL statement, test it, and then paste the SQL into the code and adding all the sqlstmt.append(" at the beginning and the ") at the end. It's 2011, isn't there a better way the handle a big chunk of strings inside code? Please: don't suggest stored procedures or ORMs. edit Found the answer using XML literals and CData. Thanks to all the people that actually tried to answer the question without questioning me for not using ORM, SPs and using VB edit 2 the question leave me thinking that languages could try to make a better effort for using inline SQL with color syntax, etc. It will be cheaper that developing Linq2SQL. Just something like: dim sql = <sql> SELECT * ... </sql>

    Read the article

  • StringBuilder vs XmlTextWriter

    - by Wololo
    I am trying to squeeze as much performance as i can from a custom HttpHandler that serves Xml content. I' m wondering which is better for performance. Using the XmlTextWriter class or ad-hoc StringBuilder operations like: StringBuilder sb = new StringBuilder("<?xml version="1.0" encoding="UTF-8" ?>"); sb.AppendFormat("<element>{0}</element>", SOMEVALUE); Does anyone have first hand experience?

    Read the article

  • Dynamically create controls using stringbuilder

    - by Shrewdy
    hi, i have been trying to create controls dynamically on my web page using the StringBuilder class..and i dont quite seem to get through... any help would be appreciated. i am trying to do this... StringBuilder sbTest = new StringBuilder(string.Empty); sbTest.Append("<input type=\"text\" id=\"txt1\" runat=\"server\" />"); Response.Write(sbTest.ToString()); The page for sure displays a TextBox on the browser which is easily accessible through JavaScript...but what i want is the control to be available on the Server Side too...so that when the page is posted back to the server i can easliy obtain the value that has been entered by the user into the textbox. Can any 1 please help me with this.... thank you so much....

    Read the article

  • when to use StringBuilder in java

    - by kostja
    It is supposed to be generally preferable to use a StringBuilder for String concatenation in Java. Is it always the case? What i mean is : Is the overhead of creating a StringBuilder object, calling the append() method and finally toString() smaller then concatenating existing Strings with + for 2 Strings already or is it only advisable for more Strings? If there is such a threshold, what does it depend on (the String length i suppose, but in which way)? And finally - would you trade the readability and conciseness of the + concatenation for the performance of the StringBuilder in smaller cases like 2, 3, 4 Strings?

    Read the article

  • Fastest way to pad a number in Java to a certain number of digits

    - by Martin
    Am trying to create a well-optimised bit of code to create number of X-digits in length (where X is read from a runtime properties file), based on a DB-generated sequence number (Y), which is then used a folder-name when saving a file. I've come up with three ideas so far, the fastest of which is the last one, but I'd appreciate any advice people may have on this... 1) Instantiate a StringBuilder with initial capacity X. Append Y. While length < X, insert a zero at pos zero. 2) Instantiate a StringBuilder with initial capacity X. While length < X, append a zero. Create a DecimalFormat based on StringBuilder value, and then format the number when it's needed. 3) Create a new int of Math.pow( 10, X ) and add Y. Use String.valueOf() on the new number and then substring(1) it. The second one can obviously be split into outside-loop and inside-loop sections. So, any tips? Using a for-loop of 10,000 iterations, I'm getting similar timings from the first two, and the third method is approximately ten-times faster. Does this seem correct? Full test-method code below... // Setup test variables int numDigits = 9; int testNumber = 724; int numIterations = 10000; String folderHolder = null; DecimalFormat outputFormat = new DecimalFormat( "#,##0" ); // StringBuilder test long before = System.nanoTime(); for ( int i = 0; i < numIterations; i++ ) { StringBuilder sb = new StringBuilder( numDigits ); sb.append( testNumber ); while ( sb.length() < numDigits ) { sb.insert( 0, 0 ); } folderHolder = sb.toString(); } long after = System.nanoTime(); System.out.println( "01: " + outputFormat.format( after - before ) + " nanoseconds" ); System.out.println( "Sanity check: Folder = \"" + folderHolder + "\"" ); // DecimalFormat test before = System.nanoTime(); StringBuilder sb = new StringBuilder( numDigits ); while ( sb.length() < numDigits ) { sb.append( 0 ); } DecimalFormat formatter = new DecimalFormat( sb.toString() ); for ( int i = 0; i < numIterations; i++ ) { folderHolder = formatter.format( testNumber ); } after = System.nanoTime(); System.out.println( "02: " + outputFormat.format( after - before ) + " nanoseconds" ); System.out.println( "Sanity check: Folder = \"" + folderHolder + "\"" ); // Substring test before = System.nanoTime(); int baseNum = (int)Math.pow( 10, numDigits ); for ( int i = 0; i < numIterations; i++ ) { int newNum = baseNum + testNumber; folderHolder = String.valueOf( newNum ).substring( 1 ); } after = System.nanoTime(); System.out.println( "03: " + outputFormat.format( after - before ) + " nanoseconds" ); System.out.println( "Sanity check: Folder = \"" + folderHolder + "\"" );

    Read the article

  • Does string concatenation use StringBuilder internally?

    - by JamesBrownIsDead
    Three of my coworkers just told me that there's no reason to use a StringBuilder in place of concatenation using the + operator. In other words, this is fine to do with a bunch of strings: myString1 + myString2 + myString3 + myString4 + mySt... The rationale that they used was that since .NET 2, the C# compiler will build the same IL if you use the + operator as if you used a StringBuilder. This is news to me. Are they correct?

    Read the article

  • StringBuilder/StringBuffer vs. "+" Operator

    - by matt.seil
    I'm reading "Better, Faster, Lighter Java" (by Bruce Tate and Justin Gehtland) and am familiar with the readability requirements in agile type teams, such as what Robert Martin discusses in his clean coding books. On the team I'm on now, I've been told explicitly not to use the "+" operator because it creates extra (and unnecessary) string objects during runtime. But this article: http://www.ibm.com/developerworks/java/library/j-jtp01274.html Written back in '04 talks about how object allocation is about 10 machine instructions. (essentially free) It also talks about how the GC also helps to reduce costs in this environment. What is the actual performance tradeoffs between using "+," "StringBuilder," or "StringBuffer?" (In my case it is StringBuffer only as we are limited to Java 1.4.2.) StringBuffer to me results in ugly, less readable code, as a couple of examples in Tate's book demonstrates. And StringBuffer is thread-synchronized which seems to have its own costs that outweigh the "danger" in using the "+" operator. Thoughts/Opinions?

    Read the article

  • Hibernate: OutOfMemoryError persisting Blob when printing log message

    - by paul
    I have a Hibernate Entity: @Entity class Foo { //... @Lob public byte[] getBytes() { return bytes; } //.... } My VM is configured with a maximum heap size of 512 MB. When I try to persist an object which has a 75 MB large object, I get an OutOfMemoryError. The names of the methods in the stack trace (StringBuilder, ByteArrayBlobType.toLoggableString, pretty.Printer.toString) suggest that hibernate is trying to write a very large log message that contains my object. Am I correct about why hibernate is using so much memory? What is the simplest way to work around this problem? java.lang.OutOfMemoryError: Java heap space at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:44) at java.lang.StringBuilder.<init>(StringBuilder.java:81) at org.hibernate.type.ByteArrayBlobType.toString(ByteArrayBlobType.java:117) at org.hibernate.type.ByteArrayBlobType.toLoggableString(ByteArrayBlobType.java:127) at org.hibernate.pretty.Printer.toString(Printer.java:53) at org.hibernate.pretty.Printer.toString(Printer.java:90) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:97) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.jboss.seam.persistence.HibernateSessionProxy.flush(HibernateSessionProxy.java:181)

    Read the article

  • WTSVirtualChannelRead Only reads the first letter of the string.

    - by Scott Chamberlain
    I am trying to write a hello world type program for using virtual channels in the windows terminal services client. public partial class Form1 : Form { public Form1() { InitializeComponent(); } IntPtr mHandle = IntPtr.Zero; private void Form1_Load(object sender, EventArgs e) { mHandle = NativeMethods.WTSVirtualChannelOpen(IntPtr.Zero, -1, "TSCRED"); if (mHandle == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } private void button1_Click(object sender, EventArgs e) { uint bufferSize = 1024; StringBuilder buffer = new StringBuilder(); uint bytesRead; NativeMethods.WTSVirtualChannelRead(mHandle, 0, buffer, bufferSize, out bytesRead); if (bytesRead == 0) { MessageBox.Show("Got no Data"); } else { MessageBox.Show("Got data: " + buffer.ToString()); } } protected override void Dispose(bool disposing) { if (mHandle != System.IntPtr.Zero) { NativeMethods.WTSVirtualChannelClose(mHandle); } base.Dispose(disposing); } } internal static class NativeMethods { [DllImport("Wtsapi32.dll")] public static extern IntPtr WTSVirtualChannelOpen(IntPtr server, int sessionId, [MarshalAs(UnmanagedType.LPStr)] string virtualName); //[DllImport("Wtsapi32.dll", SetLastError = true)] //public static extern bool WTSVirtualChannelRead(IntPtr channelHandle, long timeout, // byte[] buffer, int length, ref int bytesReaded); [DllImport("Wtsapi32.dll")] public static extern bool WTSVirtualChannelClose(IntPtr channelHandle); [DllImport("Wtsapi32.dll", EntryPoint = "WTSVirtualChannelRead")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WTSVirtualChannelRead( [In()] System.IntPtr hChannelHandle , uint TimeOut , [Out()] [MarshalAs(UnmanagedType.LPStr)] System.Text.StringBuilder Buffer , uint BufferSize , [Out()] out uint pBytesRead); } I am sending the data from the MSTSC COM object and ActiveX controll. public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { rdp.Server = "schamberlainvm"; rdp.UserName = "TestAcct"; IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx(); secured.ClearTextPassword = "asdf"; rdp.CreateVirtualChannels("TSCRED"); rdp.Connect(); } private void button1_Click(object sender, EventArgs e) { rdp.SendOnVirtualChannel("TSCRED", "Hello World!"); } } //Designer code // // rdp // this.rdp.Enabled = true; this.rdp.Location = new System.Drawing.Point(12, 12); this.rdp.Name = "rdp"; this.rdp.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("rdp.OcxState"))); this.rdp.Size = new System.Drawing.Size(1092, 580); this.rdp.TabIndex = 0; I am getting a execption every time NativeMethods.WTSVirtualChannelRead runs Any help on this would be greatly appreciated. EDIT -- mHandle has a non-zero value when the function runs. updated code to add that check. EDIT2 -- I used the P/Invoke Interop Assistant and generated a new sigiture [DllImport("Wtsapi32.dll", EntryPoint = "WTSVirtualChannelRead")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WTSVirtualChannelRead( [In()] System.IntPtr hChannelHandle , uint TimeOut , [Out()] [MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer , uint BufferSize , [Out()] out uint pBytesRead); it now receives the text string (Yea!) but it only gets the first letter of my test string(Boo!). Any ideas on what is going wrong? EDIT 3 --- After the call that should of read the hello world; BytesRead = 24 Buffer.Length = 1; Buffer.Capacity = 16; Buffer.m_StringValue = "H";

    Read the article

  • String Object. Clarification needed

    - by mac
    Guys, help me clarify. Say i have the following line in my program: jobSetupErrors.append("abc"); In the case above where jobSetupErrors is a StringBuilder(), what i see happen is: New String Object is created and assigned value "abc" value of that String object is assigned to the existing StringBuilder object If that is correct, and I add 1 more line ... jobSetupErrors.append("abc"); logger.info("abc"); In the above example are we creating String object separately 2 times? If so, would it be more proper to do something like this? String a = "abc"; jobSetupErrors.append(a); logger.info(a); Is this a better approach? Please advise

    Read the article

  • the error in the stringbuilder

    - by Kubi
    string rowString = "<tr id=\"row1\" bgcolor=\"#FFFFFF\" onMouseOver=\"this.bgColor='#EEEEEE';\" onMouseOut=\"this.bgColor='#FFFFFF';\" style=\"cursor:pointer;\">" + "<td bgcolor=\"#FFFFFF\"><img src=\"images/"+"-companylogofilename-"+"\" width=\"108\" height=\"32\" alt=\""+"-companyname-"+"\" /></td>" + //turkish.airlines.jpg airlineiconfilename, airline name "<td class=\"table_content\">{0}</td>" + "<td class=\"table_content\">{1}</td>" + "<td class=\"table_content\">{2}</td>" + "<td class=\"table_content\">{3}</td>" + "<td class=\"table_content\">{4}</td>" + "<td class=\"table_content\"><table width=\"98%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" + "<tr><td class=\"table_content\">{5}</td>" + "<td width=\"20\" align=\"right\">" + "<a href=\"default.aspx\" onClick=\"return hs.htmlExpand(this, { headingText: '{6} - {7}', width: 600, height: 215, targetX: 'row1 400px', targetY: 'row1 40px' })\">" + "<img src=\"images/arrow.png\" width=\"13\" height=\"16\" border=\"0\" class=\"tip\" onMouseOver=\"tooltip('Click for Details.');\" onMouseOut=\"exit();\" />" + "</a>"; accordionHTML.Append(String.Format(rowString, flight.Get_AirlineCode(), flight.Get_Clase(), flight.Get_Departure(), flight.Get_DeprtDate(), flight.Get_DeprtTime(), flight.Get_Destination(), flight.Get_Departure(), flight.Get_Destination())); Hi, Can someone please help me to find the mistake above ? I am getting an error as "Input string was not correct !"; Thanks in advance,

    Read the article

  • Android: Speeding up display of (html-formatted) text

    - by prepbgg
    My app uses a StringBuilder to assemble paragraphs of text which are then displayed in a TextView within a ScrollView. The displaytext.xml layout file is: <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFFFFF" xmlns:android="http://schemas.android.com/apk/res/android"> <ScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/display_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#000000" > </TextView> </ScrollView> </LinearLayout> and the code that displays the StringBuilder object sbText is setContentView(R.layout.displaytext); TextView tv = (TextView)findViewById(R.id.display_text); tv.setText(Html.fromHtml(sbText.toString())); This works OK, except that it gets very slow as the amount of text grows. For example, to display 50 paragraphs totalling about 50KB of text takes over 5 seconds just to execute those three lines of code. Can anyone suggest how I can speed this up, please?

    Read the article

  • SQL DataReader how to show null-values from query

    - by cc0
    I have a DataReader and a StringBuilder (C#.NET) used in the following way; while (reader.Read()) { sb.AppendFormat("{0},{1},{2},",reader["Col1"], reader["Col2"], reader["Col3"]); } Which works great for my use, but when a row is null I need it to return "null", instead of just "". What would be a good way of accomplishing that? Suggestions are very appreciated

    Read the article

  • optimize a string.Format + replace.

    - by acidzombie24
    I have this function. The visual studio profile marked the line with string.Format as hot and were i spend much of my time. How can i write this loop more efficiently? public string EscapeNoPredicate(string sz) { var s = new StringBuilder(sz); s.Replace(sepStr, sepStr + sepStr); foreach (char v in IllegalChars) { string s2 = string.Format("{0}{1:X2}", seperator, (Int16)v); s.Replace(v.ToString(), s2); } return s.ToString(); }

    Read the article

  • How to maxmise the largest contiguous block of memory in the Large Object Heap

    - by Unsliced
    The situation is that I am making a WCF call to a remote server which is returns an XML document as a string. Most of the time this return value is a few K, sometimes a few dozen K, very occasionally a few hundred K, but very rarely it could be several megabytes (first problem is that there is no way for me to know). It's these rare occasions that are causing grief. I get a stack trace that starts: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.Xml.BufferBuilder.AddBuffer() at System.Xml.BufferBuilder.AppendHelper(Char* pSource, Int32 count) at System.Xml.BufferBuilder.Append(Char[] value, Int32 start, Int32 count) at System.Xml.XmlTextReaderImpl.ParseText() at System.Xml.XmlTextReaderImpl.ParseElementContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlTextReader.Read() at System.Xml.XmlReader.ReadElementString() at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderMDRQuery.Read2_getMarketDataResponse() at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer2.Deserialize(XmlSerializationReader reader) at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle) at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) I've read around and it is because the Large Object Heap is just getting too fragmented, so even preceding the call with a quick check to StringBuilder.EnsureCapacity just causes the OutOfMemoryException to be thrown earlier (and because I'm guessing at what's needed, it might not actually need that much so my check is causing more problems than it is solving). Some opinions are that there's not much I can do about it. Some of the questions I've asked myself: Use less memory - have you checked for leaks? Yes. The memory usage goes up and down, but there's no fundamental growth that guarantees this to happen. Some of the times it fails, it succeeded at that stage previously. Transfer smaller amounts Not an option, this is a third party web service over which I have no control (or at least it would take a long time to resolve, in the meantime I still have a problem) Can you do something to the LOH to make it less likely to fail? ... now this is most fruitful course. It's a 32-bit process (it has to be for various political, technical and boring reasons) but there's normally hundreds of meg free (multiples of the largest amount for which we've seen failures). Can we monitor the LOH? Using perfmon I can track the size of the heaps, but I don't think there's a way to monitor the largest available contiguous block of memory. Question is: any advice or suggestions for things to try?

    Read the article

  • Using string[] as a Dictionary key e.g. Dictionary<string[], StringBuilder>

    - by Nick Allen - Tungle139
    The structure I am trying to achieve is a composite Dictionary key which is item name and item displayname and the Dictionary value being the combination of n strings So I came up with var pages = new Dictionary<string[], StringBuilder>() { { new string[] { "food-and-drink", "Food & Drink" }, new StringBuilder() }, { new string[] { "activities-and-entertainment", "Activities & Entertainment" }, new StringBuilder() } }; foreach (var obj in my collection) { switch (obj.Page) { case "Food": case "Drink": pages["KEY"].Append("obj.PageValue"); break; ... } } The part I am having trouble with is accessing the Dictionary Key pages["KEY"] How do I target the Dictionary Key whose value at [0] == some value? Hope that makes sense

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >