json - How to avoid unnecessary object creation in Java in a for loop -


i creating following json file using java

jsonobject json = new jsonobject(); jsonarray vertex = new jsonarray(); (int = 0; < num; i++) {     jsonobject usr1 = new jsonobject();     jsonobject usr2 = new jsonobject();      // string na="name"+i     usr1.put("type", "string");     usr1.put("value", "name" + i);     usr2.put("name", usr1);      usr2.put("_id", integer.tostring(i));     usr2.put("_type", "vertex");     // v2.put(usr2);     vertex.put(usr2);      // email     jsonobject usr3 = new jsonobject();     jsonobject usr4 = new jsonobject();     usr3.put("type", "string");     usr3.put("value", "email" + + "@gmail.com");     usr4.put("email", usr3);      usr4.put("_id", integer.tostring(i + num));     usr4.put("_type", "vertex");     vertex.put(usr4); } json.put("vertex", vertex); 

the num can approx 60,000-200,000.

but on here creating java objects again , again, quite expensive. want object creation minimized don't want change code structure much. how can achieve without changing code structure much?

i'm using json* classes org.codehaus.jettison.json package.and have write file json object

for fast json generation without creating intermediate objects jsonwriter used:

stringwriter sw = new stringwriter(); jsonwriter writer = new jsonwriter(sw); writer.object().key("vertex").array(); (int = 0; < num; i++) {     writer         .object() // usr2             .key("name")                 .object() // usr1                     .key("type").value("string")                     .key("value").value("name"+i)                 .endobject()             .key("_id").value(integer.tostring(i))             .key("_type").value("vertex")         .endobject()         .object() // usr4             .key("email")                 .object() // usr3                     .key("type").value("string")                     .key("value").value("email"+i+"@gmail.com")                 .endobject()             .key("_id").value(integer.tostring(i+num))             .key("_type").value("vertex")         .endobject(); } writer.endarray().endobject(); string json = sw.tostring(); 

here stringwriter used store intermediate json text. alternatively may write directly file or network socket without keeping in memory @ all.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -