SlideShare a Scribd company logo
1 of 40
Why learn internals?
By: Shaul Rosenzweig
Part 1: collection hell
Bit on ArrayList, StringBuilder, etc
● Backed by Java array
● Constructor allocates initial 4-16 bytes (depends on implementation)
● When it is filled, it doubles array size and copies the memory
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b b , _
a b c
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _ f g h
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _ f g h , _
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _ f g h , _
o
a b c , _ d e , _ f g h , _ m n
Copy and GC
OkHttp old disk cache code, called by Picasso
for (int x = 0; x < valueCount; x++) {
cleanFiles[x] = new File(directory, key + "." + x);
dirtyFiles[x] = new File(directory, key + "." + x + ".tmp");
}
What really happens...
for (int x = 0; x < valueCount; x++) {
StringBuilder b1 = new StringBuilder();
b1.append(key);
b1.append(".");
b1.append(x);
cleanFiles[x] = new File(directory, b1.toString());
StringBuilder b2 = new StringBuilder();
b2.append(key);
b2.append(".");
b2.append(x);
b2.append(".tmp");
dirtyFiles[x] = new File(directory, b2.toString());
}
Optimized code
StringBuilder b = new StringBuilder(key);
b.append(".");
int truncateTo = b.length();
for (int x = 0; x < valueCount; x++) {
b.append(x);
cleanFiles[x] = new File(directory, b.toString());
b.append(".tmp");
dirtyFiles[x] = new File(directory, b.toString());
b.setLength(truncateTo);
}
Part 2: multidex hell
How many methods? 0?
class MyClass {
}
How many methods? 1?
$ javac MyClass.java
$ javap MyClass.class
Class MyClass {
MyClass();
}
How many methods? 2?
$ dx --dex --output=myclass.dex
MyClass.class
$ dexdump -f myclass.dex
method_ids_size : 2
$ dex-method-list myclass.dex
MyClass <init>()
java.lang.Object <init>()
Inner classes
public class Outer {
private static String getStatic(String name) {
return "Hello " + name;
}
private class Inner {
void doSomething(OtherObj other, String name)
{
other.setGreeting(Outer.getStatic(name));
}
Inner classes do not exist, extra method
$ javac Outer.java
$ ls
Outer.class
Outer.java
Outer$Inner.class
$ javap -p Outer.class
class Outer {
Outer();
private static java.lang.String displayText(…);
static java.lang.String access$000(…);
}
What javac did? This code does the same
public class Outer {
private static String getStatic(String name) {
return "Hello " + name;
}
}
private class Outer$Inner {
void doSomething(OtherObj other, String name) {
other.setGreeting(Outer.getStatic(name));
}
}
WTF is this access$000 method?
$ javap -p -c Outer
class Outer{
...
static java.lang.String access$000(…);
Code:
0: aload_0
1: invokestatic #1 // Method getStatic:…
4: areturn
}
Accessor method bomb
class AccessorMethodBomb{
private int count;
private Inner inner;
@Override protected void doSomething(Bundle state) {
inner = new Inner() {
@Override public void blah() {
count = 0;
++count;
--count;
count++;
count--;
...
6 accessors and 2 constructors added
class AccessorMethodBomb {
AccessorMethodBomb();
Object();
protected void doSomething();
static int access$002(AccessorMethodBomb, int); // count = 0 write
static int access$004(AccessorMethodBomb); // ++count preinc
static int access$006(AccessorMethodBomb); // --count predec
static int access$008(AccessorMethodBomb); // count++ postinc
static int access$010(AccessorMethodBomb); // count-- postdec
static int access$000(AccessorMethodBomb); // count read
}
Common problem
● Inner classes added to compiler in Java 1.1 with accessor method trick
○ VM is not inner class aware
○ Quick and dirty addition: inner class is really a separate class
○ If there is no access, accessor method is added by javac
● Optimizers do not solve this problem
● Common problem: Facebook app has 5000 avoidable accessor methods
● Similar situation in most 3rd party libs and apps
● Slows down method lookup
● Triggers need for multidex much sooner than needed
Part 3: GC compactor
Moving garbage collector
● Added in ART
● Two compaction modes:
○ Semi-space for low mem devices, Homogenous for normal
● Compacts fragmented memory
● Can’t work when process is active
● Result of it not working: fragmented memory
● Let the app rest, let the compactor compact!
Part 4: in praise of zygote
Zygote tidbits
● Zygote system service is started by init.rc as parent of all Java apps
● Loads Android framework into memory and waits on a socket
● When app runs, zygote forks, and original one runs the app
● Copy on write - framework memory is read only, so it never changes
● All apps use same Android framework code loaded in RAM
● On PC, every JVM instance loads its own copy of Java framework
● Slow start speed and big memory footprint
● Android runs Java in similar way like servers
Part 5: CPU cache is your friend
How does it influence execution speed?
int[] arr = new int[64 * 1024 * 1024];
//does 100% of work and takes measured 80ms
for (int i = 0; i < arr.Length; i++) arr[i] *= 3;
//does 6% of the work and takes measured 78ms
for (int i = 0; i < arr.Length; i += 16) arr[i] *= 3;
ARM cache architecture
ARM big.LITTLE cache architecture
CPU 1 (fast) CPU 2 (slow)
Memory reference latency
● Register reference: too fast to be measured
● L1 cache reference: 0.5 ns
● L2 cache reference: 7ns
● RAM reference: 100ns
As function of step
for (int i = 0; i < arr.Length; i += K) arr[i] *= 3;
How to minimize cache misses
● While data is being read, CPU cycles idle away
● Less read latency = less sleep cycles
● L1 cache is 200 times faster than DRAM
● Volume: 32k L1 data cache, 512k-4mb L2 cache
● L2 is shared between cores, so less mide be available
● Keep data in sequential buffers
● OOP Objects tend to scatter data in memory
● CPU reads memory in cache lines of 64 bytes
● Cache misses: bad, cache hits: good
Part 6: NAND flash endurance
NAND flash write endurance
● Stores charge behind floating gate, which degrades on writes
● TLC and MLC flash has 500-3000 write cycles
● Controller tries to spread the writes out to mitigate the effect
● When worn down, device starts getting bad sectors
● Bad sectors cause kernel to remount partition as read-only
● Application that is constantly writing to storage will wear it down
● Try to cache writes, do not flush every byte, if possible use removable
storage which can be replaced

More Related Content

What's hot

Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
Sages
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variables
Teerawat Issariyakul
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
aleks-f
 

What's hot (20)

Engineering fast indexes
Engineering fast indexesEngineering fast indexes
Engineering fast indexes
 
Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)
 
Protostar VM - Heap3
Protostar VM - Heap3Protostar VM - Heap3
Protostar VM - Heap3
 
#2 (UDP)
#2 (UDP)#2 (UDP)
#2 (UDP)
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
tokyotalk
tokyotalktokyotalk
tokyotalk
 
DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright
 
Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
RedisConf17- durable_rules
RedisConf17- durable_rulesRedisConf17- durable_rules
RedisConf17- durable_rules
 
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variables
 
Intro to Rust from Applicative / NY Meetup
Intro to Rust from Applicative / NY MeetupIntro to Rust from Applicative / NY Meetup
Intro to Rust from Applicative / NY Meetup
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
 
Swug July 2010 - windows debugging by sainath
Swug July 2010 - windows debugging by sainathSwug July 2010 - windows debugging by sainath
Swug July 2010 - windows debugging by sainath
 
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 

Similar to Why learn Internals?

JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
guest3eed30
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
Wei Lin
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
Computer Science Club
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
Kernel TLV
 

Similar to Why learn Internals? (20)

PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centre
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
 
PPU Optimisation Lesson
PPU Optimisation LessonPPU Optimisation Lesson
PPU Optimisation Lesson
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Linux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudLinux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloud
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
Exploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran LonikarExploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran Lonikar
 
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen TatarynovWorkshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
 
Project Tungsten: Bringing Spark Closer to Bare Metal
Project Tungsten: Bringing Spark Closer to Bare MetalProject Tungsten: Bringing Spark Closer to Bare Metal
Project Tungsten: Bringing Spark Closer to Bare Metal
 
PythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesPythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummies
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 

More from Shaul Rosenzwieg (8)

Brainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a proBrainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a pro
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Android Open Accessory
Android Open AccessoryAndroid Open Accessory
Android Open Accessory
 
Lifecycle of a pixel
Lifecycle of a pixelLifecycle of a pixel
Lifecycle of a pixel
 
Secure Android Development
Secure Android DevelopmentSecure Android Development
Secure Android Development
 
Android virtual machine internals
Android virtual machine internalsAndroid virtual machine internals
Android virtual machine internals
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 

Why learn Internals?

  • 1. Why learn internals? By: Shaul Rosenzweig
  • 3. Bit on ArrayList, StringBuilder, etc ● Backed by Java array ● Constructor allocates initial 4-16 bytes (depends on implementation) ● When it is filled, it doubles array size and copies the memory StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 4. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 5. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 6. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 7. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c
  • 8. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b b , _ a b c
  • 9. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e
  • 10. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _
  • 11. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _ f g h
  • 12. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _ f g h , _
  • 13. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _ f g h , _ o a b c , _ d e , _ f g h , _ m n Copy and GC
  • 14. OkHttp old disk cache code, called by Picasso for (int x = 0; x < valueCount; x++) { cleanFiles[x] = new File(directory, key + "." + x); dirtyFiles[x] = new File(directory, key + "." + x + ".tmp"); }
  • 15. What really happens... for (int x = 0; x < valueCount; x++) { StringBuilder b1 = new StringBuilder(); b1.append(key); b1.append("."); b1.append(x); cleanFiles[x] = new File(directory, b1.toString()); StringBuilder b2 = new StringBuilder(); b2.append(key); b2.append("."); b2.append(x); b2.append(".tmp"); dirtyFiles[x] = new File(directory, b2.toString()); }
  • 16. Optimized code StringBuilder b = new StringBuilder(key); b.append("."); int truncateTo = b.length(); for (int x = 0; x < valueCount; x++) { b.append(x); cleanFiles[x] = new File(directory, b.toString()); b.append(".tmp"); dirtyFiles[x] = new File(directory, b.toString()); b.setLength(truncateTo); }
  • 18. How many methods? 0? class MyClass { }
  • 19. How many methods? 1? $ javac MyClass.java $ javap MyClass.class Class MyClass { MyClass(); }
  • 20. How many methods? 2? $ dx --dex --output=myclass.dex MyClass.class $ dexdump -f myclass.dex method_ids_size : 2 $ dex-method-list myclass.dex MyClass <init>() java.lang.Object <init>()
  • 21. Inner classes public class Outer { private static String getStatic(String name) { return "Hello " + name; } private class Inner { void doSomething(OtherObj other, String name) { other.setGreeting(Outer.getStatic(name)); }
  • 22. Inner classes do not exist, extra method $ javac Outer.java $ ls Outer.class Outer.java Outer$Inner.class $ javap -p Outer.class class Outer { Outer(); private static java.lang.String displayText(…); static java.lang.String access$000(…); }
  • 23. What javac did? This code does the same public class Outer { private static String getStatic(String name) { return "Hello " + name; } } private class Outer$Inner { void doSomething(OtherObj other, String name) { other.setGreeting(Outer.getStatic(name)); } }
  • 24. WTF is this access$000 method? $ javap -p -c Outer class Outer{ ... static java.lang.String access$000(…); Code: 0: aload_0 1: invokestatic #1 // Method getStatic:… 4: areturn }
  • 25. Accessor method bomb class AccessorMethodBomb{ private int count; private Inner inner; @Override protected void doSomething(Bundle state) { inner = new Inner() { @Override public void blah() { count = 0; ++count; --count; count++; count--; ...
  • 26. 6 accessors and 2 constructors added class AccessorMethodBomb { AccessorMethodBomb(); Object(); protected void doSomething(); static int access$002(AccessorMethodBomb, int); // count = 0 write static int access$004(AccessorMethodBomb); // ++count preinc static int access$006(AccessorMethodBomb); // --count predec static int access$008(AccessorMethodBomb); // count++ postinc static int access$010(AccessorMethodBomb); // count-- postdec static int access$000(AccessorMethodBomb); // count read }
  • 27. Common problem ● Inner classes added to compiler in Java 1.1 with accessor method trick ○ VM is not inner class aware ○ Quick and dirty addition: inner class is really a separate class ○ If there is no access, accessor method is added by javac ● Optimizers do not solve this problem ● Common problem: Facebook app has 5000 avoidable accessor methods ● Similar situation in most 3rd party libs and apps ● Slows down method lookup ● Triggers need for multidex much sooner than needed
  • 28. Part 3: GC compactor
  • 29. Moving garbage collector ● Added in ART ● Two compaction modes: ○ Semi-space for low mem devices, Homogenous for normal ● Compacts fragmented memory ● Can’t work when process is active ● Result of it not working: fragmented memory ● Let the app rest, let the compactor compact!
  • 30. Part 4: in praise of zygote
  • 31. Zygote tidbits ● Zygote system service is started by init.rc as parent of all Java apps ● Loads Android framework into memory and waits on a socket ● When app runs, zygote forks, and original one runs the app ● Copy on write - framework memory is read only, so it never changes ● All apps use same Android framework code loaded in RAM ● On PC, every JVM instance loads its own copy of Java framework ● Slow start speed and big memory footprint ● Android runs Java in similar way like servers
  • 32. Part 5: CPU cache is your friend
  • 33. How does it influence execution speed? int[] arr = new int[64 * 1024 * 1024]; //does 100% of work and takes measured 80ms for (int i = 0; i < arr.Length; i++) arr[i] *= 3; //does 6% of the work and takes measured 78ms for (int i = 0; i < arr.Length; i += 16) arr[i] *= 3;
  • 35. ARM big.LITTLE cache architecture CPU 1 (fast) CPU 2 (slow)
  • 36. Memory reference latency ● Register reference: too fast to be measured ● L1 cache reference: 0.5 ns ● L2 cache reference: 7ns ● RAM reference: 100ns
  • 37. As function of step for (int i = 0; i < arr.Length; i += K) arr[i] *= 3;
  • 38. How to minimize cache misses ● While data is being read, CPU cycles idle away ● Less read latency = less sleep cycles ● L1 cache is 200 times faster than DRAM ● Volume: 32k L1 data cache, 512k-4mb L2 cache ● L2 is shared between cores, so less mide be available ● Keep data in sequential buffers ● OOP Objects tend to scatter data in memory ● CPU reads memory in cache lines of 64 bytes ● Cache misses: bad, cache hits: good
  • 39. Part 6: NAND flash endurance
  • 40. NAND flash write endurance ● Stores charge behind floating gate, which degrades on writes ● TLC and MLC flash has 500-3000 write cycles ● Controller tries to spread the writes out to mitigate the effect ● When worn down, device starts getting bad sectors ● Bad sectors cause kernel to remount partition as read-only ● Application that is constantly writing to storage will wear it down ● Try to cache writes, do not flush every byte, if possible use removable storage which can be replaced