0

Which of the below ways of adding to a HashMap is more efficient (considering both time and space efficiency)?

Way 1:

Music foo = new Music(Files.getMusic("bar/bold.mp3"));
HashMap.put("rock", foo);

Way 2:

HashMap.put("rock", new Music(Files.getMusic("bar/bold.mp3")));
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
julian
  • 4,634
  • 10
  • 42
  • 59
  • 1
    Identical. Local "temporary" variables are essentially "free" in Java. So the first sequence is preferred because it's easier to read and understand. – Hot Licks Feb 16 '14 at 21:15

2 Answers2

1

this is identical. Java objects are passed by reference, you have the exact same number of objects created in both cases.

Omry Yadan
  • 31,280
  • 18
  • 64
  • 87
1

Both are the exact same. When running

new Music(Files.getMusic("bar/bold.mp3"));

You create an object in memory, and return a reference to it. Whether you temporarily store that reference in foo before passing it to the HashMap or not doesn't really make a difference (and even if it would, this would be optimized away).

PaF
  • 3,297
  • 1
  • 14
  • 15