亲测String, StringBuffer和StringBuilder计算速度
String 为不可变类型,一旦赋值,重新赋值相当于重新new
StringBuffer 是线程安全的,也就是同步的,重新赋值不会重新new,效率高于String
StringBuilder是非线程安全的,也就是异步的,重新赋值也不会重新new,效率更高。
下面是亲测数据:
String 增加 “c” 运行20万次与 StringBuffer 运行20万次对比:
运行时间为:19246ms
StringBuffer 运行20万次:
运行时间为:仅12ms 是不是比string快很多,那么StringBuilder就不用20万次了,因为计算次数太小,下面用1亿次计算
String运行1亿次直接死机
StringBuffer StringBuilder 各运行1亿次
运行时间为:2660ms
StringBuilder 运行1亿次
运行时间:915ms, 速度最快
测试结果表:
20万次计算 | 1亿次计算 | |
string(旧对象被GC回收) | 19246ms | 死机 |
StringBuffer(线程安全) | 12ms | 2660ms |
StringBuilder(非线程安全) | 小于3ms | 915ms |