在Java程序中,创建对象、打印输出到屏幕、启动线程到底需要发
费多长时间?针对这个最基本的问题,做了如下测试:
测试硬件环境:
联想扬天E3100,AMD Sempron 64位 2600+(约1.6Ghz),512M内存,80G硬盘
测试软件环境:
测试软件环境:
Eclipse3.2.2+JDK5.0,直接在Eclipse下运行
测试代码:
public
class
TestCreatObject
...
{

public static void main(String[] args) ...{
long start=System.currentTimeMillis();
for(int i=0;i<10000;i++)...{
String str=new String(""+i );
}
long end1=System.currentTimeMillis();
for(int i=0;i<10000;i++)
System.out.println(i);
long end2=System.currentTimeMillis();
for(int i=0;i<10000;i++)...{
TestThread tt=new TestThread();
tt.start();
}
System.out.println("create object time:"+(end1-start));
System.out.println("print screen time:"+(end2-end1));
System.out.println("start thread time:"+( System.currentTimeMillis()-end2));
}


}

class
TestThread
extends
Thread
...
{
public void run()...{
// try {
// sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}

测试结果:
create object time:32
print screen time:218
start thread time:1844
print screen time:218
start thread time:1844
对线程测试时,该线程运行的时间和启动速度是什么关系呢 ?原来的线程本身没有执行任何东西,现在把屏蔽的代码打开 ,把sleep()的时间分别从1-》10-》100- 》1000-》10000,结果如下:
1-》start thread time:2110
10-》start thread time:2297
100-》start thread time:2594
1000-》start thread time:5672
10000-》start thread time:49875
结果分析:
1.在Java程序当中,创建对象所花费的时间几乎可以忽略不计
2.打印输出到屏幕因为涉及到IO操作,需要花费一定的时间,约每次0.0218ms,在对系统性能要求不是很高,基本不会影响程序性能的发挥
3.启动大量并发线程需要发费较多的时间,并且虽然线程本身运行时间的长短,花费的时间也直线上升 ,看来多线程处理并不是线程越多越好,要有一个适当的度才能最大程 度的发挥系统的性能,当线程的运行时间更长时可能导致内存越界异常
本文探讨了在Java程序中创建对象的基本操作,并进行了性能测试。涵盖了多线程环境下对象的生成、字符串拼接和类加载等方面,揭示了内存管理和效率的最佳实践。

6679

被折叠的 条评论
为什么被折叠?



