SlideShare a Scribd company logo
A look behind              the scenes



                greenDAO


Droidcon Berlin 2012,
Markus Junginger
About me, Follow me
     Android developer since 2007
     Founder of greenrobot.de, Munich
     @green_dao Most updates      
     @greenrobot_de
     Most important updates       
     +Markus Junginger            
     +greenrobot                  
Agenda
 What is greenDAO?
  – SQLite database
  – ORM
  – Code generation based on meta model
 Background info and „secret“ internals
  – Why code generation?
  – Performance Tweaks
Problem with DB Development
   Database world  ||  Java world
   No object orientation
   Data access feels quite low levely
   A lot of boilerplate code for SQLite
    – SQL scripts, e.g.: CREATE TABLE, Queries
    – Cursor iterations
    – Parameter binding
Common solution: ORM
                                Java Object
      SQLite
                  greenDAO        Java Object
     Database
                                Java Object



 ORM offers a higher level API
  – Read and write objects
  – CREATE TABLE done for you
  – Expressing Queries
Example: SQLite vs. greenDAO
String[] columns = { "note", "date_changed" };
String[] idArgs = { String.valueOf(id) };
SQLiteCursor cursor = (SQLiteCursor) db.query("notes", columns,
"_id=?", idArgs, null, null, "note");
try {
           // greenDAO
  if (cursor.getCount() != 1) {
           Note note = noteDao.load(id);
    throw new Exception("Unexpected count: " +cursor.getCount());
           updateUi(note.getNote(), note.getDate());
  }
  cursor.moveToNext();
  String note = cursor.getString(0);
  String date = cursor.getString(1);
  updateUi(note, date);
} finally {
  cursor.close();
}
greenDAO Overview
 Entities & DAOs
 Code generation
 Open Source:
  https://github.com/greenrobot/greenDAO
 Apache 2 license: core library
  (embedded in your app)
 GPL3: generator
  (you usually don‘t have changes here)
greenDAO Structure
Generator Project                              Android Project
  (Plain Java)

                                               Sources
 Schema-Model
 • Entities
 • Properties                                   Generated
 • Relations                                    Sources
                    greenDAO Code Generation
 • Indexes, …                                   • Entities
                                                • DAOs

 greenDAO
 Generator Lib                                 greenDAO
 +FreeMarker                                   Core Lib
Code Generation: Meta Model
 In generator project
 Defines data model
  (your schema)
 Define with Java
Example: Model for Generator
Schema schema = new Schema(1,
  "de.greenrobot.daoexample");

Entity simple = schema.addEntity("Note");
simple.addIdProperty();
simple.addStringProperty("text").notNull();
simple.addDateProperty("date");

new DaoGenerator().generateAll(
  "../DaoExample/src-gen", schema);
Example: Generated Entity
public class Note {
    private String text;
    // ID, date and constructors skipped

    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}
Code: Insert, Update, Delete
Note note = new Note();
note.setText(“Say hello to world”);
noteDao.insert(note);
Log.d("Dao", “New ID: " + note.getId());

note.setText(“Save the world”);
noteDao.update(note);

noteDao.delete(note);
QueryBuilder
 References generated Properties
 Java Complier checks
 Example: Get all users with first name
  “Joe“, and sort by last name
  List<User> joes = userDao.queryBuilder()
  .where(Properties.FirstName.eq("Joe"))
  .orderAsc(Properties.LastName)
  .list();
Entity relations
   Entity type relates to another entity type
   Supports to-one and to-many relations
   Unidirectional
   Bidirectional: requires manual updates
ToOne Example
 Entities Customer & Order
 An order has one customer
 Modelling in the generator project
 Property customerId = order.addLongProperty(
   "customerId").notNull().getProperty();
 order.addToOne(customer, customerId);

 Resolving in the app
 Customer customer = order.getCostumer();
ToMany Example
 Entities Customer & Order
 A customer places many orders
 Modelling in the generator project
 Property customerId = order.addLongProperty(
   "customerId").notNull().getProperty();
 customer.addToMany(order, customerId);

 Resolving in the app
 List<Order> orders = costumer.getOrderList();
Active Entities
 Have (some) persistence methods
  – update
  – delete
  – refresh
greenDAO Design Goals
 Maximum Performance
 Low resource usage
  – Memory consumption
  – Library size
 Easy-to-use API
 Focus on the essentials
 Optimized for Android
Save size, keep it the DRY way
 Generate code, but as sparly as possible
 Example: load method of DAO
 AbstractDao class (core library)
  – Implements everything expect readEntity
 Generated DAO implements readEntity
  – Just construct entities from a cursor position
 Library size: 59 KByte + some K per DAO
3 Basic Performance Rules
1. Group DB changes into a transaction!
   Can be like 500 times faster; still a FAQ
2. Don’t forget database indexes
3. Use prepared statements (precompiled)
Regular Performance Tracking
 Different scenarios are tested
 Tracked in Excel files
 Excel files are pushed to github
Why Code Generation?
 Annotation-based solutions: common with
  JEE ORMs (Hibernate, JPA)
 Parsing of annotations  start-up time
 Android & annotations:
  getting/setting values requires reflection
 Reflection quite slow on Android (n. slide)
 Code generation to avoid reflection
Reflection Performance
Method      Reflection (roughly)
getInt      ~ 50 x slower
getString   ~ 50 x slower
setInt      ~ 400 x slower
setString   ~ 150 x slower

 Example: 100,000 Operations
  (e.g. 10,000 entities with 10 properties)
 setInt: 9 ms, reflected 3875ms
Profiling to find hotspots
 Use traceview
 Enable in code:
 Debug.
 startMethodTracing(
 traceName);
 See class
  PerformanceTest
Reading entities & Constructor
 Entities read from the database
 Solution 1: Calling setters
 MyEntity myEntity = new MyEntity();
 myEntity.setX(cursor.getString(0));
 …
 Solution 2: Constructor only
 MyEntity myEntity = new MyEntity(
   cursor.getString(0), …);

 Performance gain: 33%
Optimization Candidate: Cursor
 Quite some time is spent in Android API
 android.database.AbstractWindowedCursor
 get… Methods are “slow”
 @Override
  public short getShort(int columnIndex) {
      checkPosition();
      return mWindow.getShort(mPos, columnIndex);
  }

  @Override
  public int getInt(int columnIndex) {
      checkPosition();
      return mWindow.getInt(mPos, columnIndex);
  }
Custom Cursor implementation
 Replacing SQLiteCursor
 de.greenrobot.dao.FastCursor
 Performance gain: ~30%
Lookup by ID
 Identity Scope (≈ Entity Caching)
 Mapping ID  Entity
 HashMap<Long, MyEntity>
  Problem: Long object creation
 LongSparseArray<MyEntity>
  Problem: does not scale
 Evaluated several alternatives
LongHashMap & More
   Custom de.greenrobot.dao.LongHashMap
   + Locking improvements
   + Minor performance tweaks
   Performance gain: from 30% up to 117%
Performance: Entities / Second




Measured on a Nexus S (1 GHz), Android 2.3
Performance comparison




Measured on a Nexus S (1 GHz), Android 2.3
Current Workflow vs. Migration
 Works best if you start from scratch
  (Start with Entity modeling)
 Migration: additional effort required
  – Pre-existing entities: have to be replaced
  – Existing tables: entities have to modeled
 Ideas how to address migration
  – Generic DAO (Annotation based entities!)
  – Import existing Model from SQLite DB files
Current Feature Requests
 Generate Adapters, CRUD Apps,
  Parceable, conversion to JSON/XML, …
 Convenience support for async ops
 Client/Server(Cloud) data synchronization
 More flexible primary keys (PKs)
 Pre- and post persist callbacks
 What is most important to you?
Disclaimer, Rechtliches
 Alle Inhalte urheberrechtlich geschützt.
  © Copyright 2011 Markus Junginger
  All rights reserved.
 Kontakt: markus@greenrobot.de
 http://greenrobot.de
 http://twitter.com/#!/greenrobot_de

More Related Content

What's hot

Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
Jeff Yemin
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
MongoDB
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
MongoDB
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
Rebecca Grenier
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
MongoDB
 
Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0
Victor Coustenoble
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
Reducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQLReducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQL
MongoDB
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
Scott Leberknight
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
Knoldus Inc.
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329
Douglas Duncan
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
MongoDB
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
Tomas Jansson
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
e-Legion
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
antoinegirbal
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
Knoldus Inc.
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
Requery overview
Requery overviewRequery overview
Requery overview
Sunghyouk Bae
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDB
MongoDB
 

What's hot (20)

Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
 
Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Reducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQLReducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQL
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDB
 

Viewers also liked

Dependency injection
Dependency injectionDependency injection
Dependency injection
Yuki Matsumura
 
AndroidでActiveRecordライクにDBを使う
AndroidでActiveRecordライクにDBを使うAndroidでActiveRecordライクにDBを使う
AndroidでActiveRecordライクにDBを使う
Fujimura Munehiko
 
Green dao 3.0
Green dao 3.0Green dao 3.0
Green dao 3.0
彥彬 洪
 
リアクティブプログラミング
リアクティブプログラミングリアクティブプログラミング
リアクティブプログラミング
Yuuki Takano
 
Mvp in practice
Mvp in practiceMvp in practice
Mvp in practice
彥彬 洪
 
実践アニメーション
実践アニメーション実践アニメーション
実践アニメーション
Naoya Yunoue
 
Android lint-srp-practice
Android lint-srp-practiceAndroid lint-srp-practice
Android lint-srp-practice
cch-robo
 
What is tested by pre-launch (security) reports?
What is tested by pre-launch (security) reports?What is tested by pre-launch (security) reports?
What is tested by pre-launch (security) reports?
ak_shio_555
 
全てSになる -RxJavaとLWSを持ち込む楽しさ-
全てSになる -RxJavaとLWSを持ち込む楽しさ-全てSになる -RxJavaとLWSを持ち込む楽しさ-
全てSになる -RxJavaとLWSを持ち込む楽しさ-
Ryutaro Miyashita
 
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
Masataka Kono
 
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigiReact Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
Yukiya Nakagawa
 

Viewers also liked (11)

Dependency injection
Dependency injectionDependency injection
Dependency injection
 
AndroidでActiveRecordライクにDBを使う
AndroidでActiveRecordライクにDBを使うAndroidでActiveRecordライクにDBを使う
AndroidでActiveRecordライクにDBを使う
 
Green dao 3.0
Green dao 3.0Green dao 3.0
Green dao 3.0
 
リアクティブプログラミング
リアクティブプログラミングリアクティブプログラミング
リアクティブプログラミング
 
Mvp in practice
Mvp in practiceMvp in practice
Mvp in practice
 
実践アニメーション
実践アニメーション実践アニメーション
実践アニメーション
 
Android lint-srp-practice
Android lint-srp-practiceAndroid lint-srp-practice
Android lint-srp-practice
 
What is tested by pre-launch (security) reports?
What is tested by pre-launch (security) reports?What is tested by pre-launch (security) reports?
What is tested by pre-launch (security) reports?
 
全てSになる -RxJavaとLWSを持ち込む楽しさ-
全てSになる -RxJavaとLWSを持ち込む楽しさ-全てSになる -RxJavaとLWSを持ち込む楽しさ-
全てSになる -RxJavaとLWSを持ち込む楽しさ-
 
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
 
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigiReact Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
 

Similar to Green dao

NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
Thodoris Bais
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
Murat Yener
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
Tobias Trelle
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
Hassan Abid
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
David Noble
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
Ahmad Arif Faizin
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
Jose Manuel Pereira Garcia
 
ObjectBox - The new Mobile Database
ObjectBox - The new Mobile DatabaseObjectBox - The new Mobile Database
ObjectBox - The new Mobile Database
greenrobot
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Red Hat Developers
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
scdn
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
Sunghyouk Bae
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
Tobias Trelle
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
Roberto Franchini
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Cleaning your architecture with android architecture components
Cleaning your architecture with android architecture componentsCleaning your architecture with android architecture components
Cleaning your architecture with android architecture components
Debora Gomez Bertoli
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
helenmga
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.
Tobias Trelle
 

Similar to Green dao (20)

NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
ObjectBox - The new Mobile Database
ObjectBox - The new Mobile DatabaseObjectBox - The new Mobile Database
ObjectBox - The new Mobile Database
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Cleaning your architecture with android architecture components
Cleaning your architecture with android architecture componentsCleaning your architecture with android architecture components
Cleaning your architecture with android architecture components
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.
 

More from Droidcon Berlin

Droidcon de 2014 google cast
Droidcon de 2014   google castDroidcon de 2014   google cast
Droidcon de 2014 google cast
Droidcon Berlin
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
Droidcon Berlin
 
crashing in style
crashing in stylecrashing in style
crashing in style
Droidcon Berlin
 
Android industrial mobility
Android industrial mobility Android industrial mobility
Android industrial mobility
Droidcon Berlin
 
Details matter in ux
Details matter in uxDetails matter in ux
Details matter in ux
Droidcon Berlin
 
From sensor data_to_android_and_back
From sensor data_to_android_and_backFrom sensor data_to_android_and_back
From sensor data_to_android_and_back
Droidcon Berlin
 
droidparts
droidpartsdroidparts
droidparts
Droidcon Berlin
 
new_age_graphics_android_x86
new_age_graphics_android_x86new_age_graphics_android_x86
new_age_graphics_android_x86
Droidcon Berlin
 
5 tips of monetization
5 tips of monetization5 tips of monetization
5 tips of monetization
Droidcon Berlin
 
Testing and Building Android
Testing and Building AndroidTesting and Building Android
Testing and Building Android
Droidcon Berlin
 
Matchinguu droidcon presentation
Matchinguu droidcon presentationMatchinguu droidcon presentation
Matchinguu droidcon presentation
Droidcon Berlin
 
Cgm life sdk_droidcon_2014_v3
Cgm life sdk_droidcon_2014_v3Cgm life sdk_droidcon_2014_v3
Cgm life sdk_droidcon_2014_v3
Droidcon Berlin
 
The artofcalabash peterkrauss
The artofcalabash peterkraussThe artofcalabash peterkrauss
The artofcalabash peterkrauss
Droidcon Berlin
 
Raesch, gries droidcon 2014
Raesch, gries   droidcon 2014Raesch, gries   droidcon 2014
Raesch, gries droidcon 2014
Droidcon Berlin
 
Android open gl2_droidcon_2014
Android open gl2_droidcon_2014Android open gl2_droidcon_2014
Android open gl2_droidcon_2014
Droidcon Berlin
 
20140508 quantified self droidcon
20140508 quantified self droidcon20140508 quantified self droidcon
20140508 quantified self droidcon
Droidcon Berlin
 
Tuning android for low ram devices
Tuning android for low ram devicesTuning android for low ram devices
Tuning android for low ram devices
Droidcon Berlin
 
Froyo to kit kat two years developing & maintaining deliradio
Froyo to kit kat   two years developing & maintaining deliradioFroyo to kit kat   two years developing & maintaining deliradio
Froyo to kit kat two years developing & maintaining deliradio
Droidcon Berlin
 
Droidcon2013 security genes_trendmicro
Droidcon2013 security genes_trendmicroDroidcon2013 security genes_trendmicro
Droidcon2013 security genes_trendmicro
Droidcon Berlin
 

More from Droidcon Berlin (20)

Droidcon de 2014 google cast
Droidcon de 2014   google castDroidcon de 2014   google cast
Droidcon de 2014 google cast
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
crashing in style
crashing in stylecrashing in style
crashing in style
 
Raspberry Pi
Raspberry PiRaspberry Pi
Raspberry Pi
 
Android industrial mobility
Android industrial mobility Android industrial mobility
Android industrial mobility
 
Details matter in ux
Details matter in uxDetails matter in ux
Details matter in ux
 
From sensor data_to_android_and_back
From sensor data_to_android_and_backFrom sensor data_to_android_and_back
From sensor data_to_android_and_back
 
droidparts
droidpartsdroidparts
droidparts
 
new_age_graphics_android_x86
new_age_graphics_android_x86new_age_graphics_android_x86
new_age_graphics_android_x86
 
5 tips of monetization
5 tips of monetization5 tips of monetization
5 tips of monetization
 
Testing and Building Android
Testing and Building AndroidTesting and Building Android
Testing and Building Android
 
Matchinguu droidcon presentation
Matchinguu droidcon presentationMatchinguu droidcon presentation
Matchinguu droidcon presentation
 
Cgm life sdk_droidcon_2014_v3
Cgm life sdk_droidcon_2014_v3Cgm life sdk_droidcon_2014_v3
Cgm life sdk_droidcon_2014_v3
 
The artofcalabash peterkrauss
The artofcalabash peterkraussThe artofcalabash peterkrauss
The artofcalabash peterkrauss
 
Raesch, gries droidcon 2014
Raesch, gries   droidcon 2014Raesch, gries   droidcon 2014
Raesch, gries droidcon 2014
 
Android open gl2_droidcon_2014
Android open gl2_droidcon_2014Android open gl2_droidcon_2014
Android open gl2_droidcon_2014
 
20140508 quantified self droidcon
20140508 quantified self droidcon20140508 quantified self droidcon
20140508 quantified self droidcon
 
Tuning android for low ram devices
Tuning android for low ram devicesTuning android for low ram devices
Tuning android for low ram devices
 
Froyo to kit kat two years developing & maintaining deliradio
Froyo to kit kat   two years developing & maintaining deliradioFroyo to kit kat   two years developing & maintaining deliradio
Froyo to kit kat two years developing & maintaining deliradio
 
Droidcon2013 security genes_trendmicro
Droidcon2013 security genes_trendmicroDroidcon2013 security genes_trendmicro
Droidcon2013 security genes_trendmicro
 

Recently uploaded

Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
Shiv Technolabs
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
Baishakhi Ray
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
aakash malhotra
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
Safe Software
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
Axel Rennoch
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
Priyanka Aash
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
DianaGray10
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
HackersList
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
Brian Pichman
 

Recently uploaded (20)

Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
 

Green dao

  • 1. A look behind the scenes greenDAO Droidcon Berlin 2012, Markus Junginger
  • 2. About me, Follow me Android developer since 2007 Founder of greenrobot.de, Munich @green_dao Most updates  @greenrobot_de Most important updates  +Markus Junginger  +greenrobot 
  • 3. Agenda  What is greenDAO? – SQLite database – ORM – Code generation based on meta model  Background info and „secret“ internals – Why code generation? – Performance Tweaks
  • 4. Problem with DB Development  Database world  ||  Java world  No object orientation  Data access feels quite low levely  A lot of boilerplate code for SQLite – SQL scripts, e.g.: CREATE TABLE, Queries – Cursor iterations – Parameter binding
  • 5. Common solution: ORM Java Object SQLite greenDAO Java Object Database Java Object  ORM offers a higher level API – Read and write objects – CREATE TABLE done for you – Expressing Queries
  • 6. Example: SQLite vs. greenDAO String[] columns = { "note", "date_changed" }; String[] idArgs = { String.valueOf(id) }; SQLiteCursor cursor = (SQLiteCursor) db.query("notes", columns, "_id=?", idArgs, null, null, "note"); try { // greenDAO if (cursor.getCount() != 1) { Note note = noteDao.load(id); throw new Exception("Unexpected count: " +cursor.getCount()); updateUi(note.getNote(), note.getDate()); } cursor.moveToNext(); String note = cursor.getString(0); String date = cursor.getString(1); updateUi(note, date); } finally { cursor.close(); }
  • 7. greenDAO Overview  Entities & DAOs  Code generation  Open Source: https://github.com/greenrobot/greenDAO  Apache 2 license: core library (embedded in your app)  GPL3: generator (you usually don‘t have changes here)
  • 8. greenDAO Structure Generator Project Android Project (Plain Java) Sources Schema-Model • Entities • Properties Generated • Relations Sources greenDAO Code Generation • Indexes, … • Entities • DAOs greenDAO Generator Lib greenDAO +FreeMarker Core Lib
  • 9. Code Generation: Meta Model  In generator project  Defines data model (your schema)  Define with Java
  • 10. Example: Model for Generator Schema schema = new Schema(1, "de.greenrobot.daoexample"); Entity simple = schema.addEntity("Note"); simple.addIdProperty(); simple.addStringProperty("text").notNull(); simple.addDateProperty("date"); new DaoGenerator().generateAll( "../DaoExample/src-gen", schema);
  • 11. Example: Generated Entity public class Note { private String text; // ID, date and constructors skipped public String getText() { return text; } public void setText(String text) { this.text = text; } }
  • 12. Code: Insert, Update, Delete Note note = new Note(); note.setText(“Say hello to world”); noteDao.insert(note); Log.d("Dao", “New ID: " + note.getId()); note.setText(“Save the world”); noteDao.update(note); noteDao.delete(note);
  • 13. QueryBuilder  References generated Properties  Java Complier checks  Example: Get all users with first name “Joe“, and sort by last name List<User> joes = userDao.queryBuilder() .where(Properties.FirstName.eq("Joe")) .orderAsc(Properties.LastName) .list();
  • 14. Entity relations  Entity type relates to another entity type  Supports to-one and to-many relations  Unidirectional  Bidirectional: requires manual updates
  • 15. ToOne Example  Entities Customer & Order  An order has one customer  Modelling in the generator project Property customerId = order.addLongProperty( "customerId").notNull().getProperty(); order.addToOne(customer, customerId);  Resolving in the app Customer customer = order.getCostumer();
  • 16. ToMany Example  Entities Customer & Order  A customer places many orders  Modelling in the generator project Property customerId = order.addLongProperty( "customerId").notNull().getProperty(); customer.addToMany(order, customerId);  Resolving in the app List<Order> orders = costumer.getOrderList();
  • 17. Active Entities  Have (some) persistence methods – update – delete – refresh
  • 18. greenDAO Design Goals  Maximum Performance  Low resource usage – Memory consumption – Library size  Easy-to-use API  Focus on the essentials  Optimized for Android
  • 19. Save size, keep it the DRY way  Generate code, but as sparly as possible  Example: load method of DAO  AbstractDao class (core library) – Implements everything expect readEntity  Generated DAO implements readEntity – Just construct entities from a cursor position  Library size: 59 KByte + some K per DAO
  • 20. 3 Basic Performance Rules 1. Group DB changes into a transaction! Can be like 500 times faster; still a FAQ 2. Don’t forget database indexes 3. Use prepared statements (precompiled)
  • 21. Regular Performance Tracking  Different scenarios are tested  Tracked in Excel files  Excel files are pushed to github
  • 22. Why Code Generation?  Annotation-based solutions: common with JEE ORMs (Hibernate, JPA)  Parsing of annotations  start-up time  Android & annotations: getting/setting values requires reflection  Reflection quite slow on Android (n. slide)  Code generation to avoid reflection
  • 23. Reflection Performance Method Reflection (roughly) getInt ~ 50 x slower getString ~ 50 x slower setInt ~ 400 x slower setString ~ 150 x slower  Example: 100,000 Operations (e.g. 10,000 entities with 10 properties)  setInt: 9 ms, reflected 3875ms
  • 24. Profiling to find hotspots  Use traceview  Enable in code: Debug. startMethodTracing( traceName);  See class PerformanceTest
  • 25. Reading entities & Constructor  Entities read from the database  Solution 1: Calling setters MyEntity myEntity = new MyEntity(); myEntity.setX(cursor.getString(0)); …  Solution 2: Constructor only MyEntity myEntity = new MyEntity( cursor.getString(0), …);  Performance gain: 33%
  • 26. Optimization Candidate: Cursor  Quite some time is spent in Android API android.database.AbstractWindowedCursor  get… Methods are “slow” @Override public short getShort(int columnIndex) { checkPosition(); return mWindow.getShort(mPos, columnIndex); } @Override public int getInt(int columnIndex) { checkPosition(); return mWindow.getInt(mPos, columnIndex); }
  • 27. Custom Cursor implementation  Replacing SQLiteCursor  de.greenrobot.dao.FastCursor  Performance gain: ~30%
  • 28. Lookup by ID  Identity Scope (≈ Entity Caching)  Mapping ID  Entity  HashMap<Long, MyEntity> Problem: Long object creation  LongSparseArray<MyEntity> Problem: does not scale  Evaluated several alternatives
  • 29. LongHashMap & More  Custom de.greenrobot.dao.LongHashMap  + Locking improvements  + Minor performance tweaks  Performance gain: from 30% up to 117%
  • 30. Performance: Entities / Second Measured on a Nexus S (1 GHz), Android 2.3
  • 31. Performance comparison Measured on a Nexus S (1 GHz), Android 2.3
  • 32. Current Workflow vs. Migration  Works best if you start from scratch (Start with Entity modeling)  Migration: additional effort required – Pre-existing entities: have to be replaced – Existing tables: entities have to modeled  Ideas how to address migration – Generic DAO (Annotation based entities!) – Import existing Model from SQLite DB files
  • 33. Current Feature Requests  Generate Adapters, CRUD Apps, Parceable, conversion to JSON/XML, …  Convenience support for async ops  Client/Server(Cloud) data synchronization  More flexible primary keys (PKs)  Pre- and post persist callbacks  What is most important to you?
  • 34. Disclaimer, Rechtliches  Alle Inhalte urheberrechtlich geschützt. © Copyright 2011 Markus Junginger All rights reserved.  Kontakt: markus@greenrobot.de  http://greenrobot.de  http://twitter.com/#!/greenrobot_de