实体类是Android 开发中经常用到的一个东东,然而今天我才听说、然后了解到原来Android中的实体类的用法不应该和Java中的实体类的用法一个样。

之前学java基础的时候知道实体类这个东西都是这样的:先建一个类,然后设置几个私有属性,然后通过get和set方法供外界调用,于是到了Android中也是一样这样用,但是其实这样在Android中是不推荐的方式。


Android中推荐使用的实体类是属性公有,不必通过get和set来调用,而是外界可以直接使用,而且这样写法在速度上会比属性私有的那种通过get和set方式调用的写法快3倍。

具体的详细说明可以参考官方的介绍说明,这个是原文:

Avoid Internal Getters/Setters


In native languages like C++ it's common practice to use getters (i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++ and is often practiced in other object oriented languages like C# and Java, because the compiler can usually inline the access, and if you need to restrict or debug field access you can add the code at any time.

However, this is a bad idea on Android. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.

Without a JIT, direct field access is about 3x faster than invoking a trivial getter. With the JIT (where direct field access is as cheap as accessing a local), direct field access is about 7x faster than invoking a trivial getter.

Note that if you're using ProGuard, you can have the best of both worlds because ProGuard can inline accessors for you.


参考链接:http://developer.android.com/training/articles/perf-tips.html#GettersSetters

http://developer.android.com/training/articles/perf-tips.html

更多相关文章

  1. Android自定义属性与自定义属性的获取
  2. Intent.FLAG 属性大全
  3. Android 中 EditText 的 inputType 属性及其他常用属性详解
  4. Android studio gradle 生成字段属性值
  5. 在AndroidManifest.xml文件中的android:windowSoftInputMode属性
  6. Android 获取AndroidManifest.xml文件versionCode,versionName属
  7. ImageView的属性android:scaleType,即ImageView.setSca...
  8. Android TabLayout导航条属性的设置

随机推荐

  1. 2021-2-16:请问你知道分布式设计模式中的Q
  2. 自学第八十天
  3. 新RabbitMQ精讲,项目驱动落地,分布式事务拔
  4. Spark3大数据实时处理-Streaming+Structu
  5. 如何零基础学习编程
  6. pinpoint通过api批量设置告警
  7. 协程原理从入门到精通 每个后端开发都需
  8. Clickhouse集群性能测试(全网独家精华版)
  9. linux下挂载NTFS文件系统出现symbol look
  10. c语言开始