1 Object Oriented Programming Lecture IX Some notes on Java Performance with aspects on execution time and memory consumption.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Memory Management Chapter FourteenModern Programming Languages, 2nd ed.1.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
Chapter 10 Introduction to Arrays
Homework Any Questions?. Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Run time vs. Compile time
Alice in Action with Java
Structured Data Types and Encapsulation Mechanisms to create new data types: –Structured data Homogeneous: arrays, lists, sets, Non-homogeneous: records.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Abstract Data Types and Encapsulation Concepts
CIT241 Prerequisite Knowledge ◦ Variables ◦ Operators ◦ C++ Syntax ◦ Program Structure ◦ Classes  Basic Structure of a class  Concept of Data Hiding.
OOP Languages: Java vs C++
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Programming Languages and Paradigms Object-Oriented Programming.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Data Structures Using C++ 2E
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 2: Everything is an Object ● C++ has many non object oriented features inherited from C. It is a hybrid language meaning that it support different.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Basic Semantics Associating meaning with language entities.
1 Scope Scope describes the region where an identifier is known, and semantic rules for this.
Best Practices. Contents Bad Practices Good Practices.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 9.
Data Structure Introduction.
Programming in Java CSCI-2220 Object Oriented Programming.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
CS 261 – Data Structures Introduction to C Programming.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
Dale Roberts Object Oriented Programming using Java - Final and Static Keywords Dale Roberts, Lecturer Computer Science, IUPUI
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Computer Graphics 3 Lecture 1: Introduction to C/C++ Programming Benjamin Mora 1 University of Wales Swansea Pr. Min Chen Dr. Benjamin Mora.
Programming Languages and Paradigms Activation Records in Java.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Amortized Analysis and Heaps Intro David Kauchak cs302 Spring 2013.
ECE 750 Topic 8 Meta-programming languages, systems, and applications Automatic Program Specialization for J ava – U. P. Schultz, J. L. Lawall, C. Consel.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
Java Programming Language
Java Review: Reference Types
CS2013 Lecture 4 John Hurley Cal State LA.
Object Oriented Programming in java
Binding Times Binding is an association between two things Examples:
7 Arrays.
Introduction to Data Structure
Review for Midterm 3.
Classes and Objects Object Creation
Presentation transcript:

1 Object Oriented Programming Lecture IX Some notes on Java Performance with aspects on execution time and memory consumption

2 Last Lecture We talked about refactoring strategies –refactoring methods –refactoring by inheritance –refactoring by delegation Netbeans and GUI forms for Graphic User Interfaces

3 Today’s Talk Improving performance in Java programs –time consumption –space consumption Reference to the material in todays lecture: –Peter Sestoft, “Java performance: Reducing time and space consumption”

4 Java Compilers Java compilers cannot do all kinds of optimization that we are used to in other languages Compared to a language as C –Java is semantically more restricted and many things have to be done at run-time operations on objects bound at run-time, dynamic data structures (eg Vector) etc. It many times cannot be predicted –what is the type of an object or –which object that is being accessed untill the code is executed

5 What can we do? With some knowledge about the –semantics of the language –run-time mechanisms in the JVM –how classes in the API are implemented, we can in some cases avoid expensive run-time JVM operations by how we write the code

6 Time consumption

7 Iterative computing on invariant expressions Loops and loop-invariant expressions –avoid recomputing loop bounds for expressions when we know the value is static One example is the size() method for(int i=0; i<size()+1; i++){ … }

8 Iterative computing on invariant expressions Instead of calling size() everytime the bound is checked: –compute the loop bound once, and bind it to a local variable for(int i=0,stop=size()+1; i<stop; i++){ … }

9 Computing subexpressions Avoid recomputing the same subexpression more than once ”Bad” example: if(shapes.elementAt(i).isCircle()); if(shapes.elementAt(i).isSquare());

10 Computing subexpressions Instead, compute the subexpression once and bind the value to a local variable ”Good” example: Shape shape = shapes.elementAt(i); if(shape.isCircle()); if(shape.isSquare());

11 Computing on Arrays in loop expressions For every access in an array, an index (out-of- bounds) check is required to be performed double[] rowsum = new double[n]; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ rowsum[i]+= arr[i][j]; } }

12 Computing on Arrays in loop expressions What we can do in this example, is to compute the outer index once double[] rowsum = new double[n]; for(int i=0; i<n; i++){ double[] arri = arr[i]; //copy reference double sum = 0.0; for(int j=0; j<m; j++) sum += arr[j];//avoid checking i index rowsum[i] = sum; }

13 Constant Fields and Variables Declare –constant fields as final static –Variables as final The compiler can inline such code and precompute constant expressions Examples: final static int x = 10; final Object a;//assigned only once

14 Long If-Else chains Avoid construction of long if- else chains: if(exp){... }else if(exp){... }else if(exp){... }... else{... } Replace with a switch-case expression instead switch(exp){ case a: statement 1 case b: statement 2 Default: statement n }

15 What about ”clever one-liners” Example: int year = 0; double sum = 200.0; double[] balance = new double[100]; while((balance[year++] = sum *= 1.05) < ); Nothing is gained by such expressions, except that you get a piece of code which noone understands

16 Fields and Variables There is no run-time overhead for variables declared as local –local variables also improves clarity of the code In a method –it is faster to access local variables and parameters than accessing static values or instance (class global) variables In loops –it might be more efficient to copy a global variable into a locally created variable, and use the local inside the loop

17 String Manipulation Avoid dynamically building strings using the concatenation (+) operator: String s = ””; for(int i=0; i<n; i++){ S += ”#” + i; } This loop has quadratic execution time and can easily cause heap fragmentation

18 String Manipulation Instead, use a StringBuilder object StringBuilder sbuf = new StringBuilder; for(int i=0; i<n; i++){ sbuf.append(”#”).append(i); } However, for a sequence, using ’+’ is ok : –String s = ”(” + x + ”, ” + y + ”)”;

19 Initialized Array variables Local method variables are initialized upon method entrance –avoid declaring initialized arrays in methods When initialized array variables or tables need to be used, declare them once as instance global final static int arr = {31,28,31,30,...};

20 Methods Method calls can be executed faster if methods are declared using private, final or static For example, accessor methods (like getSize ) can often be declared final –there is usually no need for overriding such methods in inheriting sub classes

21 Input and Output For program input and output (such as file access) –use buffered streams from java.io BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream Using buffered streams can speed up input/output up by a factor of 20

22 Bulk Array Operations Bulk operations means performing operations on whole, or sub blocks of data For Arrays, there are some special operations which are usually faster than using for -loops –one reason is that only a single bound check is required

23 Bulk Array operations static void arrayCopy(src, si, dst, di,n) –In java.lang.System Many bulk methods in java.util.Arrays –equality (compare elements) –fill (initialize elements) –searching –sorting

24 Collection Classes The collection classes in java.util are well designed and implemented and can improve the speed of a program When using lists (eg LinkedList, ArrayList… ) –Avoid indexed position access, insertion or removal of elements Those methods do linear search –Example System.out.println(list.get(i));

25 Scientific Computing There are several open source libraries available for different fields of computing For scientific computing –Colt open source library Linear algebra, matrix computation, statistics, random number generators, mathematical functions If needing special routines, it is always a good idea to look around of what is available before starting implementation

26 Reducing space consumption

27 JVM memory organization The stack –method input- and return parameters, local variables The Heap –for object instances, including strings and arrays Each thread has a separate stack –each growing and shrinking by the depth of method calls The heap is joint for all threads –a garbage collector manages the heap deallocation

28 Three important aspects of memory usage Allocation rate –the rate by which a program creates new objects high rate costs in time and space Retention –the amount of live data on the heap, which is reachable from the method stacks anytime high retention cost space (and garbage collector time) Fragmentation –creating small chunks of unusable memory –Allocation of dynamically growing objects may cause memory fragmentation costs time (to search for useable space) and space (wasted fragments)

29 Instance shared variables Use static declaration for variables shared by all instances of a class –only one field created for all objects Instead of public class Car{ String brand = ”Ferrari” } we can do this public class Car{ final static String brand = ”Ferrari”; }

30 Object allocation When it is not sure the an object will be used, we can apply lazy allocation Lazy allocation means that we postpone the allocation of an object untill it is actually needed, but only once

31 Without Lazy Allocation public class car{ private Button button = new Jbutton(); public Car(){ … initialize button … } public final Jbutton getButton(){ return button; }

32 Lazy Allocation public class car{ private Button button = null; public Car(){…} public final Jbutton getButton(){ if(button == null){ button = new Jbutton(); …initialize button … } return button; }

33 Other resources J. Noble and C. Weir, Small Memory Software, Addison-Wesley, 2001 –A number of design patterns for limited memory systems