各种api性能性能优化技巧.docVIP

  • 7
  • 0
  • 约4.29千字
  • 约 20页
  • 2020-06-08 发布于江苏
  • 举报
各种API性能/编码优化技巧 温绍锦 微博 /wengaotie 性能计数单位 ? 1 sec = 1,000 ms 毫秒 = 1,000,000 μs 微秒 = 1,000,000,000 ns 纳秒 = 1,000,000,000,000 ps 皮秒 ? 访问一次内存(Cacheline)大约10~15ns 获取当前时间API性能 操作 耗时(nano) 说明 System.currentMillis() 52 在linux-2.6.18下慢10倍,大约534ns System.nano() 47 在linux-2.6.18下慢12倍,大约658ns ? 在linux老版本(2.6.18)中,System.currentMillis 的性能是很差的,如果你的程序中,大量调用需 要获取当前时间,请升级操作系统版本。Linux- 2.6.32版本以上都是好的. ? 关键在于升级操作系统 异常性能 操作 耗时(nano) new Exception() 1061 new Exception(), throw, catch 1092 new Exception().getStackTrace() 5786 获取堆栈信息 Thread.getStackTrace() 6560 new Exception(), throw, catch/none fillStackTrace 23 重载为空的fillStackTrace方法 Throw try cach 9 抛出的是同一个Exception ? 异常的开销在于fillStackTrace方法 ? fillStackTrace方法在Exception的构造函数中调用 ? try/cach/throw都是非常快的 ? Thread.getStackTrace很慢,和Exception.getStackTrace一样 慢 ? 关键在于fillStackTrace和getStackTrace这两个方法 反射性能 操作 耗时(nano) Class.newInstance 12 Constructor.new 13 Method.invoke 4 缓存了Method Field.get 15 缓存了Field Class.forname 560~1000 系统类会快一些 Class.getField 243 Class.getMethod 250 Class.getConstrcutor 100 ? 反射的性能是很好的,只要缓存了 Class/Constructor/Method/Field ? Class.forname/getField/getMethod/getConstructor都很慢 ? 关键在于缓存Class/Constructor/Field/Method等元数据对象 字符串性能(一) 第一种写法: for (int i = 0, len = str.length(); i len; ++i) { char ch = str.charAt(i); } 第二种写法: char[] chars = str.toCharArray(); for (int i = 0; i chars.length; ++i) { char ch = chars[i]; } 第一种写法比第二种写法速度更快。长度为1000的String,第一种写法 250ns,第二种写法会产生gc,700~7000都可能。 结论:charAt比toCharArray然后访问char数组快 字符串性能 ? StringBuilder是非线程安全版本的StringBuffer, 性能更好 ? 在方法内使用StringBuffer,可能会被javac编译 时替换为StringBuilder ? 他们有共同被instrinsic的方法 – 三个构造函数: () / (int) / (String) – 三个append方法:append(char) / append(int) / append(String) – toString方法 并发性能(一) 操作 耗时 nano volatile int ++ 15 volatile long int ++ 15 AtomicLong.increment() 17 AtomicInteger.increment() 17 ReentrantLock.lock/unlock 38 主要消耗在一次Cacheline上 Unfair ReentrantLock.lock/unlock 37 主要消耗在两次Cacheline上 synchronized 36 ? volatile 变量读取的性能和普通变量一样,修改 的性能很差 ? JDK 6/7中,syncrhonized性能

文档评论(0)

1亿VIP精品文档

相关文档