【DevTips】LogKt
LogKt
Debug 下输出 Log,Release 下不输出,这个很多人对这种操作都非常熟悉了。
对于 Kotlin 代码,可以使用这样的类打 Log,提高运行效率:
object LogKt {
val DEBUG = BuildConfig.*DEBUG*
inline fun debug(tag: String**,**block: () -> String) {
if (DEBUG) {
Log.d(tag**,**block())
}
}
inline fun info(tag: String**,**block: () -> String) {
if (DEBUG) {
Log.i(tag**,**block())
}
}
inline fun warn(tag: String**,**block: () -> String) {
if (DEBUG) {
Log.w(tag**,**block())
}
}
inline fun error(tag: String**,**block: () -> String) {
if (DEBUG) {
Log.e(tag**,**block())
}
}
}
使用方:
fun foo() {
LogKt.info(“test”) {
“log info”
}
}
这里利用了 inline 的特性,把产生字符串这段操作,放到在 DEBUG 判断之后,好处是:
- 在非 DEBUG(或者其他你的条件下),完全没有字符串产生
特别地,在一些会频繁调用的方法里(比如 View#onDraw),这样写可以避免频繁产生字符串对象,减少 GC 压力。
Subscribe to JuniperPhoton's Blog
Get the latest posts delivered right to your inbox