kotlin中inline、noinline、crossinline为什么会在库里面被疯狂使用(一)?

inline的使用

不是优化的场景

首先先扔出示例,以下代码模拟打印“hello,World!!!”,只不过是先打印hello,再打印world。

inline fun printWorld(){
    println("World!!!")
}

@Test
fun inlineHelloWorld(){
    print("hello,")
    printWorld()
}

当printWorld使用的inline后,它的实际效果是相当于:

fun realHelloWorld(){
    print("hello,")
    println("World!!!")
}

学过C语言的的话,这个操作其实就相当于宏替换,与宏替换一样同样可能会有代码膨胀的问题,这就相当于就是将printWorld内部的内容放入到inlineHelloWorld进行替换,实际结果就是相当于没有调用printWorld,少了一次堆栈调用,但是这个能优化性能吗,调用栈的优化,我们其实还不如当它没有。inline的出现,是为了接下来的场景优化。

inline的收益场景

大家都已经用到过lamda函数了,同时kotlin编译后的字节码是跑到jvm中,而kotlin是兼容至少java 1.6的,有考虑过lamda函数是怎么转换成java代码的吗?比如:

inline fun myPrint(action:() -> Unit){
    action()
}

其实它也是转换成对象来实现的,怎么实现的?

public final void myPrint(@NotNull Function0 action) {
  Intrinsics.checkParameterIsNotNull(action, "action");
  action.invoke();
}

也就是说对于非lamda表达式来说,lamda表达式会多创建一个对象来包裹对应的动作,也就是说每次都会多一对象创建的消耗。jvm在创建对象时,每个对象至少要消耗8个左右的byte作为对象头,还会涉及堆内容的创建与对象初始化,如果这个时候加入inline,优化效率就比较高,特别是有些频繁调用的场景下,比如在循环中调用lamda表达式。

这也就是为什么kotlin原生库中经常会加入inline的原因。比如在list的扩展方法中:

public fun <T> List<T>.firstOrNull(): T? {
    return if (isEmpty()) null else this[0]
}

public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
    for (element in this) if (predicate(element)) return element
    throw NoSuchElementException("Collection contains no element matching the predicate.")
}

其中加入firstOrNull方法并未使用inline标注,first方法因为加入了predicate判断的入参加入inline就可以起到优化作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用 Kotlin 和 Spring Boot 写的简单的 Socket 服务器的例子: 首先,我们需要添加对 Spring Boot 和 Kotlin 的依赖,我们可以在 `build.gradle` 文件添加以下内容: ```groovy dependencies { implementation("org.springframework.boot:spring-boot-starter-websocket") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") } ``` 接下来,我们可以创建一个 `WebSocketController` 类,用来处理 WebSocket 的请求: ```kotlin import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.socket.WebSocketHandler import org.springframework.web.socket.config.annotation.EnableWebSocket import org.springframework.web.socket.config.annotation.WebSocketConfigurer import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean @Controller @EnableWebSocket @RequestMapping("/socket") class WebSocketController : WebSocketConfigurer { override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) { registry.addHandler(SocketHandler(), "/socket-handler") } @GetMapping("/test") @ResponseBody fun test(): String { return "Hello World!" } // 设置 WebSocket 缓冲区的大小 fun servletServerContainerFactoryBean(): ServletServerContainerFactoryBean { val servletServerContainerFactoryBean = ServletServerContainerFactoryBean() servletServerContainerFactoryBean.maxBinaryMessageBufferSize = 1024 * 1024 servletServerContainerFactoryBean.maxTextMessageBufferSize = 1024 * 1024 return servletServerContainerFactoryBean } } class SocketHandler : WebSocketHandler { override fun afterConnectionEstablished(session: WebSocketSession) { println("Connection established!") } override fun handleMessage(session: WebSocketSession, message: WebSocketMessage<*>) { println("Received message: ${message.payload}") } override fun handleTransportError(session: WebSocketSession, exception: Throwable) { println("Transport Error!") } override fun afterConnectionClosed(session: WebSocketSession, closeStatus: CloseStatus) { println("Connection closed!") } override fun supportsPartialMessages(): Boolean { return false } } ``` 在上面的代码,`WebSocketController` 类实现了 `WebSocketConfigurer` 接口,用来注册 WebSocket 的处理程序。同时,我们还定义了一个 `SocketHandler` 类,用来处理 WebSocket 的消息。在 `WebSocketController` 类,我们还定义了一个测试用的 API,用来返回一个字符串。 最后,我们需要在 `application.properties` 文件配置 Tomcat 的 WebSocket 支持: ``` server.tomcat.max-connections=1000 server.tomcat.max-threads=200 server.tomcat.accept-count=200 server.tomcat.max-http-post-size=10000000 server.tomcat.max-swallow-size=10000000 ``` 在上面的配置,我们设置了 Tomcat 的最大连接数、最大线程数、最大 HTTP POST 大小等等。 以上就是一个简单的使用 Kotlin 和 Spring Boot 写的 Socket 服务器的例子,你可以根据自己的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值