Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pre allocating collections, maps, stringbuffer

 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This little tester seems to tell me there's very little value in specifying the size on the constructor of the classes under test. The output has tabs making it suitable for copy-paste into Excel for graphing nearly flat lines.

Tested on Java 1.4 within WSAD 5.1.2 on laptop with 1.6 ghz, 1 gig of 797mhz memory.

Does this seem like a valid test? I thought about baking up the "entryn" strings in an array before running any tests.

Does it suggest the same thing to you?

 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the value in allocating collections at the size you expect them to reach instead of letting them expand "automatically" shows up only with really large collections that strain memory management. The new array creation and copying that occurs with automatic expansion is really quite fast.

Bill
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I bet that's right. I ran this up to 100,000 entries to get it to run long enough to measure at all. It would be more interesting on a system that's already running into memory issues. I think I'm not going to bother to pre-allocate until I've seen something cause a problem.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried adding String concatenation to this to compare it to StringBuffer. The warmup() call never returned. I got bored after a few minutes and killed it. I ran it without the warmup and the elapsed time went up on a curve that was getting pretty steep early in the test. Killed again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic