• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class vs. method variable definitions  RSS feed

 
Betty Reynolds
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I am currently using a method that creates new StringBuffer and new Strings objects whenever it is invoked. I'm considering moving these items to the class, which uses this method, to be defined as private members for the sake of efficiency. The method then will simply reference these members, and, in the case of the StringBuffer, reset its length.
The method gets called about 150 times when an item change event occurs. This event could theoretically happen any number of times, but in actual usage, it probably won't be that often.
Is it worth it? What are the tradeoffs in making this decision? Thanks.
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reusing a StringBuffer is almost always a better idea than creating fresh instances of Strings and StringBuffers. The only thing you have to be wary of is that you don't hit any multi-threading issues.
If you have an improperly synchronized and protected shared buffer, and more than one thread can access the same object, the potential for wierd bugs can easily outweigh the performance gains. If your application is single-threaded I recommend reusing the buffer.
 
Betty Reynolds
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!