Java : Searching Ids from hashset or String -
i have big number of ids can store in hashset or string i.e.
string strids=",1,2,3,4,5,6,7,8,.,.,.,.,.,.,.,1000,"; or hashset<string> setofids = new hashset<string>(); setofids.put("1"); setofids.put("2"); . . . setofids.put("1000");
further more want perform search on ids
which should utilize improve performance(faster & memory efficient)
1) strids.indexof("someid"); or 2) setofids.contains("someid");
tell me other way so, can same. looking here :)
set improve choice. reasons:
search o(1)
in case of set
. in case of string
o(n)
. performance not degrade info grows. string utilize more memory if want kind of info manipulation (add or remove ids). indexof
might give negative result
say 1000 nowadays 100 not, indexof homecoming location of 1000 100 substring of 1000. simple poc code performance:
import java.util.hashset; import java.util.set; public class timecomputationtest { public static void main(string[] args) { string strids = null; set<string> setofids = new hashset<string>(); stringbuffer sb = new stringbuffer(); (int = 1;i <= 1000;i++) { setofids.add(string.valueof(i)); if (sb.length() != 0) { sb.append(","); } sb.append(i); } strids = sb.tostring(); testtime(strids, setofids, "1"); testtime(strids, setofids, "100"); testtime(strids, setofids, "500"); testtime(strids, setofids, "1000"); } private static void testtime(string strids, set<string> setofids, string string) { long starttime = system.nanotime(); strids.indexof(string); long endtime = system.nanotime(); system.out.println("string search time (" + string + ") " + (endtime - starttime)); starttime = system.nanotime(); setofids.contains(string); endtime = system.nanotime(); system.out.println("hashset search time (" + string + ") " + (endtime - starttime)); } }
the output (approx.):
string search time (1) 3000 hashset search time (1) 7000 string search time (100) 6000 hashset search time (100) 2000 string search time (500) 33000 hashset search time (500) 2000 string search time (1000) 71000 hashset search time (1000) 1000
java string search collections hashset
No comments:
Post a Comment