| Author |
Use array or Map?
|
colin shuker
Ranch Hand
Joined: Apr 11, 2005
Posts: 712
|
|
Hi, I have an odd question, but it's quite important for the chess program I'm making. I need to know which of the following two options executes faster: 1. int number=someArray[x][y]; 2. int number=((Integer)someMap.get(new Long(key))).intValue(); The problem with collections is needing to cast, then cast back. So I'm guessing second option is slower, but without all the casting, would this be quicker than option 1: 3. Integer number=(Integer)someMap.(KEY); where KEY is a Long. Thanks for any help [ April 15, 2006: Message edited by: Bear Bibeault ]
|
 |
Edwin Dalorzo
Ranch Hand
Joined: Dec 31, 2004
Posts: 961
|
|
I believe that accessing a direct memory address in an array should always be faster than looking for a key in Map. However, arrays are of immutable size, while Maps can grow dynamically, you have to take that into account. On the other hand, If you use JDK 1.5 (Tiger) you can avoid casting, at least at compile time. Best regards, Edwin Dalorzo. [ April 15, 2006: Message edited by: Edwin Dalorzo ]
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
Try using the System.currentMillis() and System.timeNanos() methods. Set a long number to the time before and after you run your method, and print out the difference. It will probably only be a microsecond or so, so you will probably find the nanosecond method more useful. If it doesn't work, it is because I have given you the wrong name for the methods. CR And I have gone back to the post to add: Remember to tell us which works faster. [ April 15, 2006: Message edited by: Campbell Ritchie ]
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56150
|
|
|
Moved to the intermediate forum.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
Good reasons to use Map: You don't know the size of the collection ahead of time, the key is not an integer but maybe something like state abbreviation, the key is a number but there will be many gaps in the key sequence. Good reasons to use index: The key is an integer, you won't skip any keys, you need fast access sequentially, maybe reverse order as well as random by key. I'm kinda making those up as I go. Do try the timing comparison and see if I was right or if it makes much difference in your situation. And hide the decision within some class so you can change it in the future without breaking any other code.
|
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
|
 |
 |
|
|
subject: Use array or Map?
|
|
|