在以前好像听说过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类,该类是一个抽象类,作用是向字符流中执行写入。
输出完成!