本站首页    管理页面    写新日志    退出


«August 2025»
12
3456789
10111213141516
17181920212223
24252627282930
31


公告
 本博客在此声明所有文章均为转摘,只做资料收集使用。

我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:
日志总数:1304
评论数量:2242
留言数量:5
访问次数:7586659
建立时间:2006年5月29日




[J2SE]关于 String的intern() 的用途 及简单测试
软件技术

lhwork 发表于 2006/8/10 9:55:29

近来要加载许多数据库数据到内存,这些数据有很多是重复的。在反复测试之后发现intern() 省了好多内存。举例如下:以下是表信息:mysql> select count(*) from t1;+----------+| count(*)   |+----------+| 8000        |+----------+1 row in set (0.01 sec) mysql> select name From t1 limit 0,1;+--------------------------------------+| name                                                  |+--------------------------------------+| 123456789123456789123456789    |+--------------------------------------+1 row in set (0.00 sec)总共8000行 ,每行的数据都是 "123456789123456789123456789"下面是类 (连接异常忽略)public static void a1() throws SQLException {  List<Po> list = new ArrayList<Po>();  Connection con = DB.getCon();  Statement stmt = con.createStatement();  ResultSet rs = stmt.executeQuery("SELECT name FROM t1");   while (rs.next()) {    String s = rs.getString(1);   Po o = new Po();   //o.setName(s); //注释掉   o.setName(s.intern());   list.add(o);   s=null;    o = null;  }rs.close();  stmt.close();  con.close(); }public static void a2() throws SQLException {  List<Po> list = new ArrayList<Po>();  Connection con = DB.getCon();  Statement stmt = con.createStatement();  ResultSet rs = stmt.executeQuery("SELECT name FROM t1");   while (rs.next()) {    String s = rs.getString(1);   Po o = new Po();o.setName(s);  list.add(o);   s=null;    o = null;  }rs.close();  stmt.close();  con.close(); }注意着色部分, a1 方法测试 使用内存: 2046544 a2 方法测试 使用内存: 3475000如果在函数的结尾加上 System.gc();  去除connection 的影响a1 方法测试 使用内存:   668856 a2 方法测试 使用内存:2262232然后再把 写函数 a3() ,把rs.getString(1) 换为 get()static String get() {  return "123456789123456789123456789123456789123456789"; }public static void a3() throws SQLException {  List<Po> list = new ArrayList<Po>();  Connection con = DB.getCon();  Statement stmt = con.createStatement();  ResultSet rs = stmt.executeQuery("SELECT name FROM t1");   while (rs.next()) {    String s = get();   Po o = new Po();o.setName(s);  list.add(o);   s=null;    o = null;  }rs.close();  stmt.close();  con.close(); }a3 方法测试 使用内存:666536    a2 (668856)比a3 的内存使用量多了一点点,这个估计就是常量池那一点内存8000条数据 差别这么大, 数据量再大的话,优势更加明显.建议大家在连接数据库查询出来的数据,用intern();注:内存使用 用 Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory() 计算


阅读全文(1993) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.502 second(s), page refreshed 144750989 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号