5

Which is a more efficient way of accessing (key,value) pairs in terms of both memory and computation: reading from a properties file using properties.getProperty("key") or loading the entire properties file into a HashMap in the beginning of the program and then looking up for the key in HashMap?

Also, if only 1 of the values from the properties is used repeatedly, will it be better to store the value in a member variable and access it or look it up each time using properties.getProperty("key")?

Andy
  • 1,080
  • 5
  • 20
  • 35

2 Answers2

15

properties.getProperty("key") is a lookup from the Hashtable that is the Properties object. When you do Properties.load(), you load the entries from a file and store them into the Properties object, which extends Hashtable. Every subsequent access to a property does a lookup in the Hashtable. There is no file IO anymore.

Of course accessing a member variable is slightly faster than accessing a value from a key in a HashMap, but I doubt that this is where you'll gain anything significant in performance. a HashMap lookup is O(1), and is damn fast. You would probably need millions of lookups before noticing a difference. Do what is the most readable for you.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I disagree with the millions of lookups. OK, if the lookups are spread over time, they probably won't make much of a difference, but if the property is accessed regularly during a longer-running operation, it should make a difference. Keep in mind that a hash lookup potentially involves traversing a (short) linked list and that the string hash code (which luckily is already cached in the string) needs to be translated to a bucket index first. Those may all be cheap operations, but they add up. – Wormbo May 25 '12 at 15:11
  • 1
    On a micro-benchmark, without any warmup phase to make sure everything is jitted and thus faster, with a Properties object containing 100 keys, it only takes 85 milliseconds to perform 1 million Properties lookups. – JB Nizet May 25 '12 at 15:18
1

Actually System.getProperty() uses a java.util.Properties object internally. The Properties class extends HashTable<Object,Object>, so sou are unlikely to gain much performance by explicitly using a HashMap instead.

However, if you are using few properties very often, it will certainly help if you store these in variables. HashTable/HashMap lookup and variable access may both be O(1), but HashTable lookup definitely has a much larger constant factor.

Wormbo
  • 4,978
  • 2
  • 21
  • 41