java大量的print影响性能吗_关于JAVA中标准输出对性能的影响

在以前好像听说过System.out.println()方法看似只是一个简单的输出方法,但是他的效率却是非常低下的。因为他的底层实现比较复杂,占用的资源非常多,于是做了一个简单的测试。

测试类如下:

/**

*

*/

package com.M.controller.test;

/**

* @author onlien zuozuo于2017年2月21日下午1:49:17编辑

* 该类对System.out.println对效率的影响进行测试,测试结果如下

* 1.当只执行自增运算时,运算速度大约为2.2亿次每秒

* 2.当执行自增并使用System.out.println输出时,速度降低2400倍

* 3.当执行自增并转码且使用System.out.println时,速度降低1600倍

*

*/

public class SpeedTest {

private static long i = 100000000000L;

private static long l = System.currentTimeMillis() + 1000L;

private static void outEncode() {

while (l >= System.currentTimeMillis()) {

System.out.println(EncodeTenToSixtyFour.encode(i++));

}

}

private static void outQuick() {

while (l >= System.currentTimeMillis()) {

i++;

}

System.out.println(i);

}

private static void outOnly() {

while (l >= System.currentTimeMillis()) {

System.out.println(i++);

}

}

public static void main(String arag[]) {

outEncode();

outQuick();

outOnly();

System.out.println(i);

}

}

下文讲解了System.out.println("hello world");的执行过程!

最简单的,System.out.println("hello world");

public void println(Object x) {

String s = String.valueOf(x);

synchronized (this) {

print(s);

newLine();

}

}

首先,"hello world"作为对象传入,然后会调用到Object的toString方法

接着,通过String.valueOf方法,得到该对象的字符串,然后用synchronized 锁掉打印的过程

public void print(String s) {

if (s == null) {

s = "null";

}

write(s);

}

在该过程中,先调用print方法,print首先对该对象进行为空检查,如果为空,就把“null”值赋给欲打印的值然后把该值传递给write方法

private void write(String s) {

try {

synchronized (this) {

ensureOpen();

textOut.write(s);

textOut.flushBuffer();

charOut.flushBuffer();

if (autoFlush && (s.indexOf('\n') >= 0))

out.flush();

}

}

catch (InterruptedIOException x) {

Thread.currentThread().interrupt();

}

catch (IOException x) {

trouble = true;

}

}

write方法通过textOut.wirte方法来执行打印。textOut是BufferedWriter的一个对象,该类继承至Object以及Writer类,该类是一个抽象类,作用是向字符流中执行写入。

输出完成!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值