通过currentThead的StackTrace获得ClassName速度测试2206021307

70 阅读1分钟

通过currentThead的StackTrace获得ClassName速度测试2206021307

Thread.currentThread().getStackTrace()[1].getClassName() 可获得当前类的全名

测试一下速度

测试代码👇

package stacktrace;

public class 通过currentThead的StackTrace获得ClassName速度测试2206021307 {
	
	static int amount = 100_0000;
	
	static String str;
	
	static void pln(Object o ) {System.out.println(o);}
	public static void main(String ...arguments) {
		long t1 = System.currentTimeMillis();
		
		for(int c=0; c<amount; c++) {
			str = Thread.currentThread().getStackTrace()[1].getClassName();
		}
		
		long t2 = System.currentTimeMillis();
		long cost1 = t2-t1;
		
		pln("执行了 "+amount/10000+" 万次, 花费时间 "+cost1+" 毫秒");
		
	}

}

执行了 100 万次, 花费时间 1339 毫秒