一、字符串格式化
String.format()的使用
二、字符串拼接
字符串拼接性能比较
三、日志打印效率
- 使用"+"号拼接字符串并打印(效率较高)
long memory1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long time1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
String name = "name" + i;
String description = "description" + i;
Log.d(TAG, "zwm, value: " + String.valueOf(i) + ", name: " + name + ", description: " + description);
}
long time2 = System.currentTimeMillis();
long memory2 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Log.d(TAG, "zwm, time: " + (time2-time1));
Log.d(TAG, "zwm, memory: " + (memory2-memory1));
03-28 21:31:12.026 30318-30318/com.tomorrow.newfeature D/MainActivity: zwm, time: 266
03-28 21:31:12.026 30318-30318/com.tomorrow.newfeature D/MainActivity: zwm, memory: 6242304
- 使用String.format()拼接字符串并打印(效率较低)
long memory1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long time1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
String name = "name" + i;
String description = "description" + i;
Log.d(TAG, String.format("zwm, value: %s, name: %s, description: %s", String.valueOf(i), name, description));
}
long time2 = System.currentTimeMillis();
long memory2 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Log.d(TAG, "zwm, time: " + (time2-time1));
Log.d(TAG, "zwm, memory: " + (memory2-memory1));
03-28 21:34:49.709 32386-32386/com.tomorrow.newfeature D/MainActivity: zwm, time: 1238
03-28 21:34:49.709 32386-32386/com.tomorrow.newfeature D/MainActivity: zwm, memory: 18251776
网友评论