数据格式化与性能优化

package data;


import java.text.MessageFormat;


public class DataFormat {
final static int N = 25000;


public static void main(String[] args) {
operatorFormat();
withPrecompileFormat();
withoutPrecompileFormat();
}

/**
* @author 梅园浩
* @date 2015年9月14日 上午11:19:12
* @category 通过预编译的方式格式化数据
*/
public static void withPrecompileFormat() {
Object argvec[] = new Object[2];
MessageFormat f = new MessageFormat("The square of (0,number,#) is {1,number,#}");
long startTime = System.currentTimeMillis();
for (int i = 0; i <= N; i++) {
argvec[0] = new Integer[i];
argvec[1] = new Integer(i * i);
String s = f.format(argvec);
}
long endTime = System.currentTimeMillis();
System.out.println("通过预编译的方式格式化数据:"+ (endTime - startTime));
}

/**
* @author 梅园浩
* @date 2015年9月14日 上午11:19:12
* @category 不通过预编译的方式格式化数据
*/
public static void withoutPrecompileFormat() {
Object argvec[] = new Object[2];
String f = "The square of (0,number,#) is {1,number,#}";
long startTime = System.currentTimeMillis();
for (int i = 0; i <= N; i++) {
argvec[0] = new Integer[i];
argvec[1] = new Integer(i * i);
String s = f.format(f,argvec);
}
long endTime = System.currentTimeMillis();
System.out.println("不通过预编译的方式格式化数据:"+ (endTime - startTime));
}


/** 
* @author 梅园浩
* @date 2015年9月14日 下午1:35:09
* @category 采用操作符格式化数据
*/ 
public static void operatorFormat() {
String s ; 
long startTime = System.currentTimeMillis();
for (int i = 0; i <= N; i++) {
s  = "The square of" + i + " is " + ( i * i );
}
long endTime = System.currentTimeMillis();
System.out.println("采用操作符格式化数据:"+ (endTime - startTime));
}

}


测试结果:

采用操作符格式化数据:79
通过预编译的方式格式化数据:659
不通过预编译的方式格式化数据:804


测试说明:

第一种方式是通过操作符“+”来格式化信息串;

第二种方式应用MessageFormat类通过预编译的方法来格式化一个信息串;

第三种方式是应用MessageFormat类通过不带预编译的方法来格式化一个信息串;

由上面的结果可以看出,采用操作符格式化数据是格式化数据的首选。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值