转换和泛型,性能有何不同? [英] Casting and Generics, Any performance difference?

查看:73
本文介绍了转换和泛型,性能有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在Android上进行很多编程,尽管我对JAVA感到很舒服,但是却缺少一些
关于在那里使用的核心概念的想法。

I am coding in Android a lot lately, Though I am comfortable in JAVA, but missing some ideas about core concepts being used there.

I我想知道这两个代码之间是否存在性能差异。

I am interested to know whether any performance difference is there between these 2 codes.

第一种方法:

//Specified as member variable.   
ArrayList <String> myList  = new ArrayList <String>(); 

并用作 String temp = myList.get(1);

第二种方法:

ArrayList myList  = new ArrayList(); //Specified as member variable.   

并使用

String temp1 = myList.get(1).toString();   

我知道它与转换有关。第一种方法比第二种方法
有很大的优势吗?在大多数情况下,在实际编码中我不得不使用第二种方法,因为arraylist可以采用不同的数据类型,我最终指定

I know its about casting. Does the first method has great advantage over the second, Most of the time in real coding I have to use second method because arraylist can take different data types, I end up specifying

ArrayList <Object> = new ArrayList <Object>(); 

或更通用的方式。

推荐答案

简而言之,如果存在任何性能差异,则无需担心。通用信息无论如何都不会在运行时存储,因此实际上并没有发生任何其他事情来减慢运行速度-正如其他答案所指出的那样,它甚至可能更快(尽管假设它稍微慢一些,但我仍然主张使用养成在此级别上过多地考虑性能的习惯可能是一件好事。可读性和代码质量通常比微优化更重要!

In short, there's no performance difference worth worrying about, if it exists at all. Generic information isn't stored at runtime anyway, so there's not really anything else happening to slow things down - and as pointed out by other answers it may even be faster (though even if it hypothetically were slightly slower, I'd still advocate using generics.) It's probably good to get into the habit of not thinking about performance so much on this level. Readability and code quality are generally much more important than micro-optimisations!

总之,泛型将是首选,因为它们可确保类型安全并让您的代码更易于阅读

In short, generics would be the preferred option since they guarantee type safety and make your code cleaner to read.

就您在数组列表中存储完全不同的对象类型(即与您正在使用的某些继承层次结构无关)的事实而言,这几乎绝对是您的设计有缺陷!我一方面可以统计完成此操作的次数,但这始终是一个暂时的障碍。

In terms of the fact you're storing completely different object types (i.e. not related from some inheritance hierarchy you're using) in an arraylist, that's almost definitely a flaw with your design! I can count the times I've done this on one hand, and it was always a temporary bodge.

这篇关于转换和泛型,性能有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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