Principles of Software Construction: Objects, Design, and Concurrency

Similar documents
Lesson 26: ArrayList (W08D1)

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection

Performance and Code Tuning. CSCE 315 Programming Studio, Fall 2017 Tanzir Ahmed

CS 231 Data Structures and Algorithms, Fall 2016

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Singleton. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 29

Memory Management: The Details

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Process s Address Space. Dynamic Memory. Backing the Heap. Dynamic memory allocation 3/29/2013. When a process starts the heap is empty

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Introduction to Java

Dynamic Data Structures (II)

Java Fundamentals (II)

CSC 533: Organization of Programming Languages. Spring 2005

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Lecture 7: Binding Time and Storage

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Devel::NYTProf. Perl Source Code Profiler. Tim Bunce - July 2009 Screencast available at

CMSC 330: Organization of Programming Languages

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

CS61C : Machine Structures

20 Most Important Java Programming Interview Questions. Powered by

CMSC 330: Organization of Programming Languages

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008

1.1 Your First Program

Memory Allocation II. CSE 351 Autumn Instructor: Justin Hsia

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

Fall 2017 Mentoring 9: October 23, Min-Heapify This. Level order, bubbling up. Level order, bubbling down. Reverse level order, bubbling up

Selected Questions from by Nageshwara Rao

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

Announcements/Follow-ups

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:

Field Analysis. Last time Exploit encapsulation to improve memory system performance

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Devel::NYTProf. Perl Source Code Profiler

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013

CS558 Programming Languages

Principles of Computer Science

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Charlie Garrod Michael Hilton

Programming Languages and Techniques (CIS120)

CMSC 330: Organization of Programming Languages

C11: Garbage Collection and Constructors

Object Oriented Programming Exception Handling

OHJ-306x: Software Testing Introduction to the Course Project Part 1: General Information and Project phases 1 & 2: Unit testing

Lec 7. for loops and methods

Dynamic Memory Allocation

Java Memory Management

JAVA PERFORMANCE. PR SW2 S18 Dr. Prähofer DI Leopoldseder

Announcements. Java Review. More Announcements. Today. Assembly Language. Machine Language

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Class Information ANNOUCEMENTS

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Contents. 8-1 Copyright (c) N. Afshartous

Methods. Every Java application must have a main method.

Variables and Java vs C++

Under the Hood: Data Representations, Memory and Bit Operations. Computer Science 104 Lecture 3

Lecture 6 Introduction to Objects and Classes

Overview of Java s Support for Polymorphism

Code Profiling. CSE260, Computer Science B: Honors Stony Brook University

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Computer Science II Data Structures

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency Can't live with it. Can't live without it.

Dynamic Memory Allocation

Pace University. Fundamental Concepts of CS121 1

1.1 Your First Program

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Primitive Data and Objects

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

HW1 due Monday by 9:30am Assignment online, submission details to come

C10: Garbage Collection and Constructors

CMSC 132: Object-Oriented Programming II

Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Introduction to Programming Using Java (98-388)

boolean add(object o) Method Description (from docs API ) Method Description (from docs API )

Dynamic Memory Allocation II October 22, 2008

Overview COMP Microprocessors and Embedded Systems. Lectures 18 : Pointers & Arrays in C/ Assembly

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

JAVA Programming Language Homework I - Nested Class

Transcription:

Principles of Software Construction: Objects, Design, and Concurrency Part 3: Design case studies Performance Charlie Garrod Michael Hilton School of Computer Science 1

Administriva Homework 4b due Thursday, October 19 th Reading due today: Effective Java, Items 5, 6, and 51 2

Feedback from early informal feedaback Slides: Post sooner after class Handwritten notes scanned at the end of slides Homework clarity concerns Attempting to balance need for clarity with learning skill of gleaning requirements from real problem descriptions Learning goals are explicit, and the basis for evaluation 3

Early Informal Feedback Continued Random Calling: Supports our goal of everyone participating in class We want to hear from everyone, not just the most vocal students Wrong Answers & Mistakes are Expected and Valued Goal is learning, not evaluation Feedback: slows down the class Make pass a more common and expected answer Other suggestions? 4

Learning goals for today Avoid premature optimization Know pitfalls of common APIs Understand garbage collection Ability to use a profiler 5

More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason including blind stupidity. William A. Wulf 6

Competing Design Goals Extensibility Maintainability (design for change & understanding) Performance Safety, security Stability 7

"It is far, far easier to make a correct program fast than it is to make a fast program correct." - Herb Sutter 8

Good Programs Rather than Fast Ones Information hiding: Individual decisions can be changed and improved without affecting other parts of a system Abstract interactions with the outside world (I/O, user interactions) A good architecture scales Hardware is cheap, developers are not Optimize only clear, concise, well-structured implementations, if at all Those who exchange readability for performance will lose both 9

Performance Optimizations High-level algorithmic changes No amount of low-level optimization can fix an inefficient algorithmic choice Low-level hacking 10

Before Optimization: Profiling Common wisdom: 80% of time spent in 20% of code Many optimizations have minimal impact or make performance worse Guessing problem often inefficient Use profiler to identify bottleneck Often points toward algorithmic changes (quadratic -> linear) 11

EXAMPLE: COSINE SIMILARITY 12

13

Performance prediction Performance prediction is hard Use profiler I/O can overshadow other costs Performance may not be practically relevant for many problems 14

15-313 Question Twitter famously had scalability problems and rewrote most of their system (Ruby -> Scala; Monolithic -> Microarchitecture) Was the initial monolithic design stupid? What tradeoffs to make for a startup? 15

PERFORMANCE PITFALLS (NOT ONLY IN JAVA) 16

Know the Language and its Libraries String concatenation List access Autoboxing 17

String concatenation in Java public String tostring(string[] elements) { String result = ""; for (int i = 0; i < elements.length; i++) result += elements[i]; return result; } 18

String concatenation in Java public String tostring(string[] elements) { } String result = ""; for (int i = 0; i < elements.length; i++) result = result.concat(elements[i]); return result; public String concat(string str) If the length of the argument string is 0, then this String object is returned. 19

Efficient String Concatenation public String tostring(string[] elements) { StringBuilder b = new StringBuilder(); for (int i = 0; i < elements.length; i++) b.append(elements[i]); return b.tostring(); } See implementation of StringBuilder 20

Lists List<String> l = for (int i = 0; i < l.size(); i++) if ( key.equals(l.get(i)) System.out.println( found it ); Possibly very slow; why? 21

Autoboxing: Integer vs int Integers are objects, ints are not new Integer(42) == new Integer(42)? 4.equals(4)? Integer a = 5? Math.max(12, new Integer(44))? new Integer(42) == 42? see implementation of Integer 22

Understand Autoboxing public static void main(string[] args) { Long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); } Very slow; why? 23

When to use Boxed Primitives? Keys and values in collections (need objects) Type parameters in general (Optional<Long>) Prefer primitive types over boxed ones where possible 24

Understanding Hashcode class Office { private String roomnr; private Set<Person> occupants; public boolean equals(object that) { } } Set<Office> possible problem? 25

Understanding Hashcode class Office { private String roomnr; private Set<Person> occupants; public int hashcode() { return 0; } } Set<Office> performance problem? 26

Hashcode good practice Start with nonzero constant (e.g. 17) For each significant field integrate value (result = result * 31 + c) where c: (f?1:0) for boolean (int) f for most primitives o.hashcode for objects 27

Don t worry about Overhead of method calls (e.g., strategy pattern) Overhead of object allocation (unless its millions) Multiplication vs shifting (compiler can optimize that) Performance of a single statement / microbenchmarks Recursion vs iteration 28

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Donald E. Knuth 29

GARBAGE COLLECTION 30

Explicit Memory Allocation vs. Garbage Collection Stack allocation: int x = 4; Heap allocation Point x = new Point(4, 5); Reference on stack, object on heap C-style explicit memory allocation pointstruct* x; x = malloc(sizeof(pointstruct)); x -> y = 5; x -> x = 4; free(x); 31

Garbage Collection No explicit free Elements that are no longer referenced may be freed by the JVM int foo() { Point x = new Point(4, 5); return x.x - x.y; } set.add(new Point(4, 5)); return set; 32

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html 33

Memory Leaks C: Forgetting to free memory Java: Holding on to references to objects no longer needed class Memory { static final List<Point> l = new ArrayList(10000); final HashMap<Integer, Connection> } Java: Not closing streams, connections, etc 34

Memory Leak Example class Stack { Point[] elements; int size = 0; void push(point x) { elements[++size] = x; } Point peek() { return elements[size]; } Point pop() { return elements[size--]; } } 35

Memory Leak Example class Stack { Point pop() { Point r = elements[size]; elements[size] = null; size--; return r; } } 36

Weak References References that may be garbage collected java.lang.ref.weakreference<t> java.util.weakhashmap<k,v> (weak keys) x = new WeakReference(new Point(4,5)); x.get() // returns the point, or null if garbage collected in between WeakHashMap useful for caching, when cache should not prevent garbage collection 37

References and Observers class Game { } List<WeakReference<Listener>> listeners = void addlistener(listener l) { listeners.add(new WeakReference(l)); } void fireevent() { } for (wl : listeners) { Listener l = wl.get(); } if (l!= null) l.update(); Should lists of observers be stored as weak references to avoid memory leaks? 38

Caching expensive computations (on immutable objects) class Cache { } Map<Cryptarithm, Solution> cache = new WeakHashMap<>(); Solution solve(cryptarithm c) { Solution result = cache.get(c); } if (result!= null) return result; result = c.solve(); cache.put(c, result); return result; similar caching in factories when creating objects 39