向下转换对象的时间复杂度是多少? [英] What's the time complexity for downcasting an object?

查看:28
本文介绍了向下转换对象的时间复杂度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 RPC 服务收到了一个通用的 Object 类型实例,我想将其转换为 MyClass 类型实例,此操作的时间复杂度是多少?性能对我的应用程序至关重要.(适用于 Java 和 C# 等语言)

I received a generic Object type instance from a RPC service that I want to cast to a MyClass type instance, what is the time complexity for this operation? Performance is critical to my application. (For languages like Java and C#)

示例:Employee employee = (Employee) person;PurchaseData purchaseData = (PurchaseData) genericData;

推荐答案

铸造首先是一项编译时间活动.

Casting is first of all a compile time activity.

在运行时,如果有的话,假设 O(1).你看,所有这些信息(比如类结构)在代码执行时固定.

At runtime, if at all, assume O(1). You see, all such information (like class structure) is fixed when code gets executed.

鉴于评论:假设您的对象被反序列化为类 X 的实例,那么 JVM 已经知道该对象实际上属于类 X.该对象存在于内存中,并且它的确切类只需查找一次!

Given the comment: assuming that your Object was deserialized as instance of class X, then the JVM already knows that said object is actually of class X. The object exists in memory, and its exact class is just one lookup away!

除此之外:假设您的对象通过某种 RPC 调用进入,并且它们从某种传输表示中反序列化到 JVM 对象中……您真的认为时间铸造的问题?调用远程服务可能需要几毫秒,甚至几秒.并且您担心稍后投射此类对象是否需要 5 纳秒、15 或 25 纳秒?

Beyond that: assuming that your objects come in via a some sort of RPC call, and they are deserialized from some sort of transport representation into JVM objects ... do you really think that the time for casting matters? Calling a remote service might need milli seconds, even seconds. And you worry if casting such objects later on will takes 5 nanoseconds or 15 or 25?

唯一可能导致显着性能的情况:当转换出错时,您会遇到 ClassCastException.

The only situation that can cause a significant performance: when that cast goes wrong, and you run into a ClassCastException.

这篇关于向下转换对象的时间复杂度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆