← Back to context

Comment by jimbokun

3 years ago

> please stop frigging saying it's the garbage collector and look at your crap for real lol

Because if the garbage collector is the bottleneck you need to fix your code to not produce so much garbage.

The first issue I tackled at one of the jobs I had was slow JSP page performance.

The code had some sizable chunks of JavaScript in Strings and looked at each authorization the user had. Its been awhile, but in dynamically generating that JavaScript (ICK!) it generated several megabytes of garbage Strings by doing `script = script + "little bit more";` way too many times. This was done for each page load. 8am and hundreds of people click the page to get their start of day stuff... and... server has problems.

That particular issue was fixed by changing it all to a StringBuilder.

I've yet to see any sloppy garbage creating that is on the same order of magnitude as that JSP was.

  • Must have been a long time ago. It's been almost a decade since that code pattern started getting compiled into calls to StringBuilder by javac.

    • It does... but only in one statement.

          String foo = "foo";
          foo += "bar";
      

      That is under the covers...

          String foo = "foo";
          foo = new StringBuilder(foo).append("bar");
      

      But... if you do:

          String foo = "foo";
          foo += "bar";
          foo += "qux";
      

      that becomes

          String foo = "foo";
          foo = new StringBuilder(foo).append("bar");
          foo = new StringBuilder(foo).append("qux");
      

      So, you've still created the strings: "foo", "foobar", and "foobarqux" and also a pair of StringBuilders.

      The actual code was more complicated (and bigger strings), but the issue is that each statement is its own StringBuilder.

      That prompted me to explore it and I looked at the byte code invocations at http://shagie.net/2014/08/17/what-goes-on-behind-the-scenes-...