1、final方法和非final方法性能对比
package cn.waggag.test;
/**
* @description: final方法和非final方法的性能区别
* @author: waggag
* @time: 2019/9/15
* @Company http://www.waggag.cn
*/
public class TestFinalMethod {
private static long stratTime;
private static long endTime;
private static final void hello() {
System.out.print("");
}
private static void hello1() {
System.out.print("");
}
public static void test() {
stratTime = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
hello();
}
endTime = System.nanoTime();
System.out.println(" final方法:" + (endTime - stratTime));
stratTime = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
hello1();
}
endTime = System.nanoTime();
System.out.println("非final方法:" + (endTime - stratTime));
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
test();
}
}
}
两者耗时对比:
final方法:98122500
非final方法:77297299
final方法:68597801
非final方法:65289500
final方法:63365000
非final方法:63405100
final方法:71009500
非final方法:70043200
final方法:66491899
非final方法:67053801
Process finished with exit code 0
结论:在一个被无数人喷的书《Java从入门到精通》看到定义为final的方法执行效率更高,实际测试,发现多次运行性能没有太大的差距。
2、使用缓存流后性能的提升
package cn.waggag.test;
import java.io.*;
/**
* @description: 测试缓冲流对性能的提升
* @author: waggag
* @time: 2019/9/15
* @Company http://www.waggag.cn
*/
public class TestFile {
private static long stratTime;
private static long endTime;
public static void main(String[] args){
for (int i = 0; i < 5; i++) {
try {
test();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void test() throws IOException {
File file = new File("D:/1.txt");
if(file.exists()){
file.delete();
}else{
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte[] bytes = "Hello!".getBytes();
stratTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
fileOutputStream.write(bytes);
}
endTime = System.nanoTime();
System.out.println("未使用缓存流:" + (endTime - stratTime));
stratTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
bufferedOutputStream.write(bytes);
}
endTime = System.nanoTime();
System.out.println("使用缓存流:" + (endTime - stratTime));
}
}
两者耗时对比:
未使用缓存流:65632501
使用缓存流:1713200
未使用缓存流:63325800
使用缓存流:866800
未使用缓存流:56619200
使用缓存流:609901
未使用缓存流:54597200
使用缓存流:482100
未使用缓存流:66573800
使用缓存流:688200
Process finished with exit code 0
结论:缓存是I/O的一种性能优化,使用缓存流可以大幅度的提升对于文件的读写性能。