Why didn't someone tell me?

I have been following these forums for a little while now. I was looking at one that used a StringBuffer to build strings instead of ...
String out = "";
out += "Another String...".. etc. I decided I would do a test. I know this may be stupid but I never even considered using a buffer. I was thrown into the Java world and just went with things I learned along the way. I build the following test..
// Method to test wether or not Adding items to a string
// using a string buffer.add() is faster than creating
// it other ways....
import java.lang.StringBuffer;
import java.util.Random;
public class stringMethodTest {
  private static Random generator = new Random();
  private static String[] list = {
    "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O",
    "P","Q","R","S","T","U","V","W","X","Y","Z",
    "0","1","2","3","4","5","6","7","8","9"};
  private static String give(){
    return
      list[generator.nextInt(list.length)] +
      list[generator.nextInt(list.length)] +
      list[generator.nextInt(list.length)] +
      list[generator.nextInt(list.length)] +
      list[generator.nextInt(list.length)] +
      list[generator.nextInt(list.length)] +
      list[generator.nextInt(list.length)];
  private static void buildUsingPlus(){
    // This will create a String using 4000 iterations
    // and a native String.
    String out = "";
    for(int a = 0; a < 4000; a++){
      out += give();
    System.out.println(out.length());
  private static void buildUsingPlusAndIntern(){
    // This will create a String using 4000 iterations
    // and a native String.
    String out = "";
    for(int a = 0; a < 4000; a++){
      out += give().intern();
    System.out.println(out.length());
  private static void buildUsingBuffer(){
    StringBuffer SB = new StringBuffer("");
    for(int a = 0; a < 4000; a++){
      SB.append(give());
    String out = SB.toString();
    System.out.println(out.length());
  private static void buildUsingBufferAndIntern(){
    StringBuffer SB = new StringBuffer("");
    for(int a = 0; a < 4000; a++){
      SB.append(give().intern());
    String out = SB.toString();
    System.out.println(out.length());
// main method just runs each of the above and times the execution.
// Putting all code in here truncated my post for some reason.I was amazed to see that when building a string using SbringBuffer.append(), with 4000 7 character words randomly generated, it took 0 ms compared to 7 sec or more in the +String way.  !!!!  OK.  Is this magic?  Can it really take 0 ms?  If all of my tests are true why don't more code examples I see around use StringBuffer?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

It's true... kinda. First off, the system time is only accurate to something like 1/20 of a second or so. That being said, StringBuffer is TREMENDOUSLY more efficient for that type of use than good ole' String.
In case you don't know why... Strings are immutable. They NEVER change. Everytime you want to append something to a String, you are actually creating a new instance of String. The following:String foo = "hello ";
foo += "world!";Does this: It creates an instance of String in the first line and gives it the value "hello ". In the second line, it does not just alter the value of foo. What it REALLY does is create a new instance of String with the value "hello world!" and assigns it to the reference foo. As you can see (especially with your test you did), this can cause BIG TIME performance problems if you're using a large set. Creating instances is expensive, plain and simple. (which is why they have StringBuffer at all).

Similar Messages

  • Why didn't anyone tell me you could name sprites now?

    Damn, it's about time they added this feature. I can't
    believe how long it
    took me to notice. Hooray for no more updating all the code
    every time I
    move the sprites down a channel or coding in cumbersome
    global property
    lists to keep track of where all my sprites are...

    > I still use 8.5, so no sprite naming. But an easy
    workaround was to create
    > a global variable (gSpriteNames = [:]) and use an
    onBeginSprite handler
    > like:
    Yeah, that's pretty much what I was doing (that's what I
    meant by
    "cumbersome global property lists"). The biggest problem I
    had with that
    was that I didn't know you could do
    gSpriteNames[#someSpriteName] =
    spriteNum, so I was doing it with
    gSpriteNames.addProp(#someSpriteName,spriteNum), which I
    discovered was
    creating a memory leak - every time a sprite's beginSprite
    code ran, it
    would add a duplicate value to that property list, which
    would ultimately
    get too big and crash the program, and so I had to first
    check to see that
    it wasn't already on the list before adding itself, etc. Then
    I had to then
    add code to each sprite to REMOVE itself from said property
    list on
    endSprite... At any rate, naming sprites is 100x better, so
    far about the
    only new feature in MX 2004 I can actually USE, but by itself
    well worth the
    price of upgrading.
    I just can't believe it took so long to implement this
    feature. I think
    I've been putting in a request for this on their wishlist
    after every new
    version since Director 5 or so. And when they finally did
    implement it, it
    seems like it was just quietly slipped in there - I didn't
    see mention of
    this on any of the "What's New" documents - they spent all
    their time hyping
    the Javascript support and Flash Components, which I barely
    touch. By
    contrast, this is something I will be using on probably every
    project from
    now on. In fact, I think I may load up a couple old projects
    and change
    them all so they work this way. It just makes so much more
    sense than the
    old way, and requires no scripts to implement, so it's less
    likely to screw
    up.

  • "Loop invariant code motion" Did you know this and why didn't you tell me?

    I'll provide the answer if nobody replies but I'll let y'all discover this yourself.
    Have fun,
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Solved!
    Go to Solution.

    elset191 wrote:
    Ben wrote:   
    If the LV compiler "sees" you have code in a loop that produce the same answer for every iteration it CAN move that code to execute before the loop.
    Can, or does?
    Just what I was about to ask.
    CLA, LabVIEW Versions 2010-2013

  • OS 10.6.5 corrupts DVD Studio Pro!!!!!!!! - Why didn't Apple tell us

    OS 10.6.5 corrupts DVD Studio Pro. Upgrade to 10.6.5 and you will mess up the drop zones in a number of the templates, in addition to other problems. It's a shame that Apple did not thoroughly test this update in advance. If they did, they would have discovered that it breaks one of their own Pro-Apps.
    Contrary to some other postings, Pro Kit 6.0.1 has nothing to do with it. It is 100% an OS 10.6.5 problem. HOWEVER to easily (and relatively quickly) fix the problem, all you have to do is reinstall Snow Leopard and then use the 10.6.4 Combo Updater. That's it . . . problem solved. No reinstallation of FCS necessary, no loss of settings or preferences, the computer and all your other Apps and prefs are not disturbed. Moral of the story: Stay clear of OS 10.6.5.

    For those who were totally stuck with a malfunctioning DVDSP 4.22 (an in my case running also OS X 10.6.5 and FCP 7.03, on a MAC Pro), I'd like to share my experience since I had a project due and was not going to be able to deliver. Quite an empty and frustrating feeling to say the least. Here's what I did to meet my contract obligations:
    1) Do not place your mouse over the simulator screen. Doing so crashed DVDSP every time. Instead you can use the screen remote to do some testing of your chapter markers and stories. You can also use your keyboard arrows. (My mouse is a Magic Mouse FYI).
    2. To avoid a compiling error and further test your markers, end jumps, etc., here's what I did:
    2a. First I built the project (use only the "build" function). Afterwards, You are going to use only the "format" function. At this point, select as your output destination, the "hard drive" option by using the arrows, next to "output device." After doing this, I was able to open my project with the computer's DVD player and test out my chapter markers and story.
    2b. Secondly I of course wanted to burn discs. I burned my disc using Disk Utility. You select the project having the "img" suffix. In short time I burnt 12 copies with no compiler error or other problems.
    Well, I made my deadline. I'm glad I did NOT try to go back to a previous Pro Kit as that was beyond my abilities and as Mr. Sass has pointed out, the problem in his opinion is OS 10.6.5 and not Pro Kit 6.01. And before I tackle the possibility of reinstalling Snow Leopard, I will need an idiot's guide as how to do that and be certain that's really the remedy. I'm just an aging liberal arts guy.
    I like Apple very much, but this DVDSP problem whatever its origin, forces me to follow the adage, "If it ain't broke, don't fix it" and wait until others point out the pitfalls. And for my next project, capture sixty seconds of raw footage and dare to burn a disc. If it works, fine. If not, warn your client.
    I'm sure Apple will fix the problem right after Christmas.

  • Why didn't Apple tell us?

    Nowhere in their advertising for 10.7 did I see anything about it not working with Power PC apps. I seem to recall that when OS X was launched we were well warned about how many apps would not work and we would have to upgrade them. I now have 3 apps that I use often which can't run under 10.7. I would never have downloaded it had i known this.

    It has been well known that it wouldn't be supported.  I strongly recommend reading http://www.macsurfer.com/ and always backing up your data prior to installing anything.   Yes, Apple has been surprisingly quiet, but Quicken did even go ahead a few days ago and said its 2007 version of its application would not work because of no Rosetta. At least a hint should have been up reading the specs that even lower end Intel CPUs weren't supported.   The earliest CoreDuo CoreSolo Macs aren't supported.    With those not even being supported, what chance does a PowerPC have of being supported?  Snow Leopard had Rosetta as an optional install.    To make a transitional application optional, after being standard should also be a hint that it will no longer be available at some point in the future.   Yes the writing is on the wall.   Unfortunately hints are often not enough.   Sorry to hear of your surprise.  We are just end users here.

  • I currently have 1,177 photos on my iphone (4s) but it takes up 4.9 GB of space. Why is it so large? I do not use photostream - this is simply within my "Camera Roll". Other than deleting the photos, can someone tell me another solution?

    I currently have 1,177 photos on my iphone (4s) but it takes up 4.9 GB of space. Why is it so large? I do not use photostream - this is simply within my "Camera Roll". Other than deleting the photos, can someone tell me another solution?
    My friend has over 2,000 photos on her iphone and it only used 1.7 GB of space and I know I had at one point over 3,000 photos on my phone and still had space left for more.
    Any tips are greatly appreciated!
    Thanks,
    Melissa.

    When you open your camera app, does it say "HDR on" at the top?
    HDR photos are better quality but take up much more space.
    Also, go to Settings>photos and camera.  Scroll down to "keep normal photo".  Is it on?  This feature saves a normal copy and an HDR copy of every photo you take.
    I bet your friend has this feature turned off along with the HDR as well.

  • Please can someone tell me why I cannot reinstall my upgrade from lightroom 4 (lightroom 3 installed off disc with serial no) my hard drive crashed, and I am trying to get lightroom 3; 4 and 5 back on so that I can link my catalogues and continue work. I

    Please can someone tell me why I cannot reinstall my upgrade from lightroom 4 (lightroom 3 installed off disc with serial no) my hard drive crashed, and I am trying to get lightroom 3; 4 and 5 back on so that I can link my catalogues and continue work. I cannot install lightroom 5 until the upgrades from 4 are on the pc, (lightroom 3 installed off disc but 4 is a copy of the upgrade download I got when I bought it) These serial no's are legit and  are registered under my account with adobe, but it still gives me the Big Red Cross when I put my serial no in! Please can someone help. I am at a loss. Thx Heidi

    Please can someone tell me why I cannot reinstall my upgrade from lightroom 4 (lightroom 3 installed off disc with serial no) my hard drive crashed, and I am trying to get lightroom 3; 4 and 5 back on so that I can link my catalogues and continue work. I cannot install lightroom 5 until the upgrades from 4 are on the pc, (lightroom 3 installed off disc but 4 is a copy of the upgrade download I got when I bought it) These serial no's are legit and  are registered under my account with adobe, but it still gives me the Big Red Cross when I put my serial no in! Please can someone help. I am at a loss. Thx Heidi

  • Plerase can someone tell me why I cannot reinstall my upgrade from lightroom 4 (lightroom 3 installed off disc with serial no) my hard drive crashed, and I am trying to get lightroom 3; 4 and 5 back on so that I can link my catalogues and continue work. I

    Please can someone tell me why I cannot reinstall my upgrade from lightroom 4 (lightroom 3 installed off disc with serial no) my hard drive crashed, and I am trying to get lightroom 3; 4 and 5 back on so that I can link my catalogues and continue work. I cannot install lightroom 5 until the upgrades from 4 are on the pc, (lightroom 3 installed off disc but 4 is a copy of the upgrade download I got when I bought it) These serial no's are legit and  are registered under my account with adobe, but it still gives me the Big Red Cross when I put my serial no in! Please can someone help. I am at a loss. Thx Heidi

    BrightBluephotograph wrote:
    I cannot install lightroom 5 until the upgrades from 4 are on the pc,
    You don't need to have Lightroom 3 and 4 installed on your computer to install Lightroom 5.  Just install Lightroom 5 and input your serial number for 3 in the previous version box and your serial number for 5 in the upgrade box.

  • Most of the time I get The Connection Was Reset. Can someone tell me why this happens?

    When I click on Firefox or when browsing or going from one site to the other I get "The connection was reset" then have to click on Try Again.
    Can someone tell me why this is happening?
    Thank you.
    THE CONNECTION WAS RESET again this morning. I even get this message when I click on the Firefox Icon to get on the net. When for example I download something then it returns me to their site I get The Connection Was Reset. When I uninstall a program and it sends to to their site in order to answer as to why I am uninstalling their program then I get The Connection Was Reset.
    Every time this happens I have to click on Try Again and find this to be annoying.
    This does not happen once or twice a week, it happen ALL THE TIME.
    This morning I went to Safe Mode and followed the instructions on INTERRUPTED OR RESET CONNECTION which tells us what to do but this did not work either.
    Would be great if someone was able to let me know what to do in order to prevent this message appearing all the time.

    Do not know how to delete this reply. I replied instead of editing my question. I have edited the above now.

  • Can someone tell me why the Iphone 5s 64gb is in the US $399 which is equivalent of £250 yet to buy it in the UK costs £709!!!!!

    can someone tell me why the Iphone 5s 64gb is in the US $399 which is equivalent of £250 yet to buy it in the UK costs £709!!!!!

    You're looking at the SUBSIDIZED price of the iPhone in the US that carriers offer by having the purchaser enter into a 2 year contract. 

  • Why iphone doesn't tell me when i call someone having an active call that i am on waiting?

    why iphone doesn't tell when i call someone having an active call that i am on waiting?

    hey i had the same problem, look and i fixed it just slightly tighten the 2 screws on the bottom of the phone with the tip of the knife or a small screw driver!! and now my phone works perfectly
    guys it really worked trust me

  • Every time I open my imovie app on my computer it always closes.  can someone tell me why it does that?  i already checked for updates but there is none.

    Every time I open my imovie app on my computer it always closes.  can someone tell me why it does that?  i already checked for updates but there is none.

    I would suggest trashing your iMovie Preference file. Complete instrucitons are here.
    https://discussions.apple.com/docs/DOC-4061

  • Impossible to update the softwares from the top CC menu. First the menu does'nt show the software on my computers and after a while of seaching, the icon disapear from the menu and no uptade. Can someone tell me why. Thank you

    Impossible to update the softwares from the top CC menu. First the menu does'nt show the software on my computers and after a while of seaching, the icon disapear from the menu and no uptade. Can someone tell me why. Thank you

    This is an open forum with a mix of other users and Adobe staff, not Adobe support... you need Adobe support
    Adobe contact information - http://helpx.adobe.com/contact.html may help
    -Select your product and what you need help with
    -Click on the blue box "Still need help? Contact us"

  • Can someone tell why when you delete an item in iCloud it is autmatically deleted from my MacBook Pro

    Can someone tell why when I delete an item in iCloud it is automatically deleted from my MacBook Pro and also what to do to avoid losing the data ?

    I have just received an email from the Apple Support Community (created by Kappy) with a list of useful links (created by Kappy) about how to use iCloud which I feell might help other users and which I have taken the liberty to enclose in this reply
    Apple - iCloud - Your content. On all your devices.
    Apple iCloud - Pertinent Questions
    Apple IDs and iCloud
    How to stay synced with iCloud | Crave - CNET
    iCloud Help
    iCloud- What you need to know | Macworld
    iOS 5 & iCloud Tips- Sharing an Apple ID With Your Family
    Learn more about iCloud
    iCloud- Limits for Contacts, Calendars, Reminders, and Bookmarks
    iCloud- Troubleshooting iCloud Contacts

  • After i updated my firefox from 3.16 to 4.0.1, have some websites i can't load, and they showed: " database error" but b4 i never got this problem. Can someone tell me why ?

    after i updated my firefox from 3.16 to 4.0.1, have some websites i can't load, and they showed: " database error" but b4 i never got this problem. Can someone tell me why ?

    Nothing is working and I can't find the Roboform toolbar. Your lack of direct support is really irritating- a live chat at least would be helpful.

Maybe you are looking for