Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from Properties file v/s HashMap lookup

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")?

like image 692
Andy Avatar asked May 25 '12 14:05

Andy


2 Answers

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.

like image 160
JB Nizet Avatar answered Sep 23 '22 13:09

JB Nizet


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.

like image 43
Wormbo Avatar answered Sep 23 '22 13:09

Wormbo