ISSN 0249-6399 ISRN INRIA/RR--3853--FR+ENG NTTTNTOA ERCECEE NOMTQEE NAUTOMATIQUE EN ET INFORMATIQUE EN RECHERCHE DE NATIONAL INSTITUT li ahShlz ui .Lwl,adCalsConsel Charles and Lawall, L. Julia Schultz, Pagh Ulrik pcaiainPatterns Specialization apport de recherche ave 1999 Janvier N˚3853 HM 2 THÈME

Sp ecialization Patterns

Ulrik Pagh Schultz, Julia L. Lawall, and Charles Consel

Thème 2  Génie logiciel

et calcul symb olique

Pro jet COMPOSE

Rapp ort de recherche n3853  Janvier 1999  28 pages

Abstract: oer numerous advantages for software development, but can

intro duce ineciency into the nished program. Program sp ecialization can eliminate such

overheads, but is most eective when targeted by the user to sp ecic b ottlenecks. Con-

sequently, we prop ose to consider program sp ecialization and design patterns as comple-

mentary concepts. On the one hand, program sp ecialization can optimize ob ject-oriented

programs written using design patterns. On the other hand, design patterns provide infor-

mation ab out the program structure that can guide sp ecialization. Concretely,we prop ose

specialization patterns, which describ e how to apply program sp ecialization to optimize uses

of design patterns.

In this pap er, we analyze the sp ecialization opp ortunities provided by sp ecic uses of

design patterns. Based on the analysis of each design pattern, we dene the asso ciated

sp ecialization pattern. These sp ecialization opp ortunities can b e declared straightforwardly

using the sp ecialization classes framework, develop ed in earlier work. Our exp eriments show

that such sp ecialization leads to signicant p erformance improvements.

Key-words: design patterns, program sp ecialization, ob ject-oriented programming, Java,

optimization

Résumé : tsvp

Supp orted in part by BULL, and in part by Alcatel under the Reutel 2000 contract.

Unité de recherche INRIA Rennes IRISA, Campus universitaire de Beaulieu, 35042 RENNES Cedex (France) Téléphone : 02 99 84 71 00 - International : +33 2 99 84 71 00 Télécopie : 02 99 84 71 71 - International : +33 2 99 84 71 71

Schémas de sp écialisation

Résumé : Les schémas de conception sont reconnus p our faciliter le développ ement

de programmes à ob jets. Cep endant, ils intro duisent souvent une certaine inecacité au

sein du logiciel nal. La sp écialisation de programmes est une technique particulièrement

adaptée à l'optimisation des programmes à ob jets. Toutefois, l'utilisation ecace de la

sp écialisation sur des logiciels de grande taille requiert une connaissance détaillée des goulots

d'étranglement de la part du programmeur.

Dans cet article, nous prop osons d'asso cier sp écialisation de programmes et schémas de

conception. Notre prop os est double. D'une part, la sp écialisation p ermet de supprimer les

inecacités intro duites par les schémas de conception. D'autre part, les schémas de concep-

tion fournissent des informations sur la structure du programme qui p ermettent de guider

le pro cessus de sp écialisation. Plus précisément, nous intro duisons la notion de schémas de

spécialisation an de mémoriser comment la sp écialisation de programmes p eut optimiser

l'utilisation d'un schéma de conception. Nous démontrons l'applicabilité des schémas de

sp écialisation, en caractérisant les opp ortunités de sp écialisation présentes dans plusieurs

schémas de conception. Nous intro duisons notre appro che en présentant des exemples de

programmes sp écialisés automatiquementaumoyen des schémas de sp écialisation.

Mots-clé : schémas de conception, sp écialization de programmes, programmation orientée

ob ject, Java, optimisation

Specialization Patterns 3

1 Intro duction

Design patterns, as presented by Gamma et al. [16], describ e well-tested program structures

that enhance mo dularity and co de reuse. A program written using design patterns is struc-

tured into indep endent units that interact through generic interfaces, and that evolveover

time in resp onse to changing conditions. Because design patterns are well-do cumented, their

use simplies the understanding of programs constructed from many indep endent units. The

exibility inherent in this use of generic interfaces, however, intrinsically blo cks optimiza-

tion across ob jects, and thus can carry a signicant p erformance p enalty. This issue remains

largely unaddressed in the design pattern community.

Many applications do not fully exploit the exibility oered by design patterns. For

a simple example, consider a typical use of the iterator design pattern [16], which sepa-

rates traversal of a data structure from its representation. Using the , an

implementation of a Set data structure might dene the member metho d as follows:

public class Set {

MinimalCollection coll; // underlying collection

public boolean member Object o  {

Iterator e = coll.iterator; // obtain iterator

while e.hasNext  { // while iterator has elements

Object x = e.next ; // obtain next iterator element

if x.equals o   return true;

}

return false;

}

...

}

This denition of the member metho d can b e used with any underlying MinimalCollection

implementation, letting the programmer freely cho ose the most appropriate concrete rep-

resentation for the task at hand. Nevertheless, our exp eriments show that the use of the

iterator pattern blo cks compiler optimization of the element retrieval op erations. When the

member metho d is used rep eatedly to search MinimalCollection ob jects that have the same

representation, the exibility provided by accessing the data through an abstract interface

is not needed. In this case, the member metho d can b e optimized, by replacing the generic

uses of the iterator pattern underlined in the metho d denition by direct accesses to the

1

underlying data structure. This transformation gives a sp eedup ranging from 20 to 80.

These measurements suggest that the optimizations p erformed by state-of-the-art compilers

do not completely comp ensate for the genericityintro duced by design patterns.

When the data representation is invariantover a p erio d of time, sp ecializing the program

to this representation b efore execution improves eciency. However, manual sp ecialization is

error-prone, and intro duces excessive program-maintenance overhead. Recently, automatic

program sp ecialization has b een shown to be eective in the context of ob ject-oriented

1

Exp eriments done with JDK 1.2.1 JIT and HotSp ot compilers on SPARC architecture, with array and

linked list representations of the underlying MinimalCollection data structure.

RR n3853

4 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

languages, sp ecically Java [22,28]. Automatic program sp ecialization systematically elimi-

nates b oth algorithmic and structural overheads, and consequently can signicantly improve

p erformance. For example, program sp ecialization has b een shown to b e eective for elimi-

nating overheads intro duced by software architectures [24].

Nevertheless, sp ecialization is not always b enecial; for example sp ecializing with resp ect

to to o many dierent representations can cause co de explosion. Therefore, the user must

explicitly target the sp ecializer toward particular invariants and regions of co de. The spe-

cialization classes framework prop osed byVolanschi et al. [32] provides a simple and declar-

ative notation for expressing such sp ecialization opp ortunities. Nevertheless, the problem

of identifying sp ecialization opp ortunities remains. Proling can help, however, it may not

reveal systematic structural overheads that blo ck optimization throughout the program. A

systematic approach taking into account the program design is needed.

This pap er

We observe that the use of design patterns in a program gives rise to patterns of structural

prop erties, which in turn give rise to patterns of overheads. These patterns of overheads form

patterns of opp ortunities for sp ecialization. We prop ose the use of specialization patterns

as a complement to design patterns, to describ e when, how, and why a program structured

using design patterns can b enet from sp ecialization. This approach retains the program

structuring advantages of design patterns, while relying on an automated transformation to

map generic co de into an ecient implementation. The contributions of this pap er are as

follows:

 We address the muchoverlo oked problem of p erformance of programs written using

design patterns, by analyzing the overheads systematically intro duced by the use of

design patterns.

 We describ e how to systematically apply program sp ecialization to eliminate these

overheads, automatically mapping well-structured generic implementations into mono-

lithic ecient ones.

 We dene sp ecialization patterns for three well-known design patterns: the builder

pattern, the , and the .

 We provide several examples of how sp ecialization can optimize uses of design patterns,

and provide b enchmarks showing the eect of sp ecialization on realistic versions of

these examples.

Earlier work has addressed the declaration of what to sp ecialize in the form of sp ecialization

classes [32] and how to sp ecialize in the form of a prototyp e Java sp ecializer [28]. Here, we

address the key issue of selecting where to sp ecialize.

First, Section 2 describ es our p ersp ective on design patterns, followed by Section 3,

which explains program sp ecialization. Section 4 describ es sp ecialization of design patterns

by means of sp ecialization patterns. Afterwards, Section 5 provides a substantial example, INRIA

Specialization Patterns 5

combining several design patterns. Then, Section 6 assesses the application of program

sp ecialization to uses of design patterns. Finally, Section 7 presents related work, Section 8

discusses future work, and Section 9 concludes.

Conventions: Throughout this pap er, we consider only the design patterns describ ed by

Gamma et al. [16]. Also, to make it easier to display example programs, wehave omitted

the Java visibility mo diers for elds and metho ds.

2 Design Patterns

When a software system evolves frequently, reusable and recongurable program comp o-

nents are needed. The notions of reusability and recongurability are central to ob ject-

oriented programming: reuse is provided by inheritance, while recongurabilityisachieved

by organizing the program using ob jects, which serve as comp osable building blo cks. Nev-

ertheless, these features tend to distribute functionality across the entire program. As a

result, programs that heavily exploit inheritance and ob ject comp osition can b e dicult for

programmers to understand and for compilers to optimize.

2.1 The structure of adaptable programs

The degree of adaptability in a program is determined by the ease with which the implemen-

tation can b e mo died as needs change, and the ability of the program to react to changing

conditions at run time. These issues are aected byhow classes are dened.

A simple approach to adapting a program is to dene a new class by using inheritance

to extend the state and b ehavior of an existing class. The use of inheritance eliminates the

need to reimplement generic functionality. Nevertheless, b ecause the inheritance relationship

is declared explicitly in the source program, the program must be rewritten to adapt to

changing conditions.

Rather than dening a class in terms of an existing class, a new class can be dened

using ob ject comp osition, by referring to the metho ds and lo cal state of other ob jects. Like

inheritance, ob ject comp osition eliminates the need to reimplement existing functionality.

This approach, however, also allows adaptability at run time, as the lo cal state of the

referenced ob jects changes, or as these ob jects are replaced by other ob jects resp ecting

the same interface. Dening ob jects in terms of abstract interfaces allows an ob ject to b e

replaced by another ob ject that has an unrelated implementation.

2.2 The role of design patterns

The use of inheritance and ob ject comp osition to enhance adaptability is non-trivial and

can make it dicult to understand how program comp onents t together. Design patterns

address these issues. Each design pattern fo cuses on a single problem often encountered in

developing an adaptable program, and prop oses a widely applicable solution. By following

RR n3853

6 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

a design pattern the programmer takes advantage of a well-tested program structure that

is op en for future extensions. Adaptable programs can b e describ ed in terms of the design

patterns they implement, which provides a guide as to how the functionality of the program

is likely to b e distributed among the class denitions.

Furthermore, to simplify program development and facilitate communication, programs

may be explicitly organized according to well-known design patterns, even when the full

exibility provided by the chosen design patterns is not needed. Particularly in this case,

eective optimization techniques for the kinds of programs that result from the use of design

patterns are critically needed.

2.3 Overheads intro duced by design patterns

In practice, the separation of classes using abstract interfaces implies that the metho d de-

nition asso ciated with a given metho d invo cation is often not obvious to the compiler. When

this is the case, the metho d invo cation must b e implemented as a virtual call. The use of

virtual calls divides a program into separate blo cks that must be individually optimized,

eectively erecting optimization barriers throughout the program. Virtual calls b oth de-

feat branch prediction and thereby instruction pip elining, and inhibit inlining, blo cking

subsequent traditional intra-pro cedural compiler optimizations [6, 14].

Many compilers go to great lengths to eliminate virtual calls [1, 12,13,27]; some even

make use of constrained sp ecialization techniques [10,20], such as customization [7]. Stan-

dard compiler optimizations rely on static analysis; when the metho d referenced by a metho d

call can b e determined statically, the metho d call can b e implemented using a direct call.

Calls to inherited metho ds can often b e implemented as direct calls, b ecause the inheritance

hierarchy is explicit at compile time. When a metho d of a referenced ob ject is invoked,

however, the call can only b e implemented as a direct call if it can b e statically determined

that at run time the reference always refers to an ob ject of the same typ e. This prop erty

rarely holds in large programs with complex class hierarchies that are written using design

patterns, where the p otential of the program to adapt to changing conditions is reected in

amultitude of p ossible implementations at each adaptable program p oint.

When the number of p ossible callees is limited, some compilers replace a virtual call

by a conditional that selects at call-time which callee to invoke with a direct call. This

transformation can b e directed using automatically gathered prole information, and enables

further optimizations through inlining or customization [17, 20]. However, the cost of a

runtime decision remains, and the control ow is only somewhat simplied.

These observations are illustrated by the the b enchmarks rep orted in Section 6. Using

state-of-the-art Java compiler technology, we found that programs written using design

patterns that op erate through abstract interfaces run at ab out half the sp eed of programs

that explicitly use direct calls. INRIA

Specialization Patterns 7

3 Program Sp ecialization

Program sp ecialization is the optimization of a program or a program fragment based on

information ab out the context in which it is used, thus generating a dedicated implementa-

tion. In our framework, sp ecialized metho ds are added to existing classes; no changes are

made to the class hierarchy.

One approach to automatic program sp ecialization is partial evaluation, which p erforms

aggressiveinter-pro cedural constant propagation of all data typ es, and p erforms constant

folding and control-ow simplications based on this information. Partial evaluation has

b een extensively investigated for functional [4, 8], logic [23], and imp erative [2, 3, 9] lan-

guages. This technique has b een recently extended to Java, by Schultz et al. [28], using

C as an intermediate language. The implementation combines the Harissa byteco de to C

compiler [26] with the Temp o program sp ecializer for the C language [9]. For this pap er, we

have extended this approach with an automatic translation of sp ecialized programs backto

Java.

3.1 Optimization by sp ecialization

In the context of design patterns, we are primarily interested in using sp ecialization to

eliminate virtual calls. Concretely, we would like to sp ecialize a program written using

design patterns to the typ es of the ob jects it manipulates, as well as to some of  the

values these ob jects contain. By sp ecializing the program with resp ect to a xed ob ject

structure, we safely bypass the abstract interfaces that isolate program comp onents, p ossibly

triggering other optimizations, either during sp ecialization or at compile time, and pro duce

a monolithic blo ck of optimized co de.

A partial evaluator can rarely deduce sp ecialization invariants from a large program as

precisely as a human programmer can, and sp ecialization of non-critical parts of a program

may cause unwanted overheads. Thus, sp ecialization is most eective when directed by the

user towards a limited part of the program where sp ecialization is b elieved to b e b enecial.

For this reason, the Temp o sp ecializer has b een designed to op erate on a program slice,

which can b e re-inserted into the program after sp ecialization. Such a program slice and the

invariants for which it is to be sp ecialized can be concisely describ ed using sp ecialization

classes. Sp ecialization classes insert guards into the sp ecialized program that ensure that

the sp ecialized co de is used only when the invariants are satised [32]. In the context of

design patterns, sp ecialization classes allow the programmer to sp ecialize for lo cal invariants

that only hold for the ob jects that play a role in the use of a design pattern.

3.2 Limitations of sp ecialization

The b enets of sp ecialization are limited by the degree to which the sp ecializer can propagate

the user-supplied invariants through the program, and by the utility of the transformations

triggered by these invariants. Sp ecialization by partial evaluation do es not propagate infor-

mation that in some way dep ends on values not known to the sp ecializer. Consequently,

RR n3853

8 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

this form of sp ecialization is most eective when there is a clean separation between the

terms that dep end only on explicit constants or user-supplied invariants, and the unknown

terms of the program. Sp ecialization classes can be used to provide the sp ecializer with

extra information, but b ecause of the need to react at run time when sp ecialization invari-

ants are invalidated, the use of sp ecialization classes do es add some ineciency. Excessive

propagation of invariants can also be detrimental. In particular, sp ecialization can cause

co de explosion either bytoomuch lo op unrolling, or by generating a very large number of

sp ecialized metho ds.

3.3 Sp ecialization example

As an example of automatic program sp ecialization, let us revisit the example of the Iterator,

describ ed in Section 1.

public class Set {

MinimalCollection coll; // underlying collection

public boolean member Object o  {

Iterator e = coll.iterator; // obtain iterator

while e.hasNext  { // while iterator has elements

Object x = e.next ; // obtain next iterator element

if x.equals o   return true;

}

return false;

}

...

}

We sp ecialize the use of the iterator pattern in the member metho d to the sp ecic typ e of

the iterator ob ject, thus reducing the number of virtual calls. Supp ose that the Minimal-

Collection ob ject referenced through the coll eld is known to b e an ob ject of a sp ecic

implementation class named Array, presented in the app endix. The Array data structure

always uses the ArrayIterator iterator also found in the app endix, so it is advantageous

to sp ecialize the member metho d for the coll eld b eing of Array typ e.

2

The sp ecialization invariant can b e declared using a sp ecialization class as follows:

specclass Member_Array specializes Set {

Array coll; // coll field is of type Array

void member Object o ; // specialize the member method

}

Sp ecializing according to Member_Array unfolds the references to the metho ds of the enu-

merator, yielding the following metho d:

2

To improve expressiveness, wehave slightly generalized the syntax of sp ecialization classes presented by

Volanschi et al.[32 ]. For example, we allowinvariants over formal parameters, and invariants that declare an

ob ject to have a sp ecic typ e. These extensions are straightforward to implement, and do not signicantly

changes the sp ecialization class framework. INRIA

Specialization Patterns 9

public boolean member_Array Object o  {

ArrayIterator e = new ArrayIterator Arraycoll ;

while e.current < e.max  {

Object x = e.array.elements[e.current++];

if x.equals o   return true;

}

return false;

}

The sp ecialized co de explicitly allo cates a new ArrayIterator, which is lo cal to this metho d.

It is also now explicit that the array elements are accessed sequentially within the lo op. Both

of these features can b e exploited by a compiler p erforming intra-pro cedural optimizations.

The automatically sp ecialized denition is between 20 and 80 faster than the original

denition.

Sp ecialization with resp ect to one invariant can often trigger other sp ecialization opp or-

tunities. Here, if the length of the Array ob ject is known, the sp ecializer can unroll the

lo op, so that only the co de needed to compare the unsp ecied data contained in the array

remains. Similarly, if the typ e of the elements contained in the Array ob ject is known, the

sp ecializer can select the corresp onding denition of the equals metho d, allowing the call

to b e inlined into the lo op. Thus, sp ecialization of design patterns can trigger further op-

timization: eliminating the indirection provided by the design pattern makes it p ossible to

exploit other invariants.

4 Sp ecialization Patterns

Design patterns facilitate communication of design ideas by encapsulating a characterization

of a common problem, together with a programming strategy that solves the problem, as

well as examples and do cumentation, into a single logical unit. Sp ecialization patterns

complement design patterns, by do cumenting a sp ecialization pro cess that results in an

ecient implementation.

4.1 Sp ecialization patterns: denition and use

A sp ecialization pattern describ es the overheads intrinsic in using a particular design pat-

tern, do cuments how to use sp ecialization to eliminate these overheads, and provides an

example that clearly illustrates how to sp ecialize a use of the design pattern. In addition,

a sp ecialization pattern can refer to other sp ecialization patterns, to describ e howmultiple

design patterns can b e sp ecialized together. Sp ecialization patterns not only guide sp ecial-

ization after a program has b een written, but can also help the programmer structure the

program so that subsequent sp ecialization will b e b enecial.

In the spirit of design patterns, sp ecialization patterns are based on the template of

Figure 1, ensuring a consistent format. The template includes sections that relate the

sp ecialization pattern to the design pattern, criteria for judging when it is worthwhile to

RR n3853

10 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

Name: The name of the asso ciated design pattern.

Description: A short description of the design pattern.

Extent: The program slice that is relevant when optimizing a use of the design pattern.

Overhead: Possible overheads asso ciated with use of the design pattern.

Compiler: Analysis of when these overheads are eliminated by standard compilers.

Approach: Sp ecialization strategies that eliminate the identied overheads.

Condition: The conditions under which the sp ecialization strategies can b e eectively exploited.

Sp ecialization class: Guidelines for how to write the needed sp ecialization classes, and howto

most eectively apply them.

Applicability: A rating of the overall applicability of sp ecialization to a use of the design pattern,

using the other information categories as criteria.

Example: An example of the use of sp ecialization to eliminate the identied overhead; the

example may include sp ecialization classes or textual descriptions.

Figure 1: Sp ecialization pattern template

design specialization patterns patterns specialization result

write generic program select deploy specialization specialize compile specialized patterns program

revise generic

program

Figure 2: Overview of sp ecialization pro cess.

sp ecialize a use of the design pattern, detailed instructions for sp ecializing, and nally a

sp ecialization example. Sample sp ecialization patterns are illustrated in Figures 3, 5, and 7.

Just as a design pattern takes into account dierent programming languages, a sp ecializa-

tion pattern should takeinto account dierent program sp ecializers. At the time of writing,

the only existing sp ecializer for a realistic ob ject-oriented language that the authors are

aware of is the sp ecializer describ ed bySchultz et al. [28]. In the context of this pap er, that

sp ecializer will thus serve to dene the minimal exp ected functionality. As other sp ecializers

are develop ed, the sp ecialization patterns can b e rened accordingly. INRIA

Specialization Patterns 11

Figure 2 shows how sp ecialization patterns t into the software development pro cess.

Once the program is written, sp ecialization opp ortunities are identied as indicated by the

sp ecialization patterns corresp onding to the design patterns used in the program. Sp ecial-

ization classes are then written as suggested by the selected sp ecialization patterns. The

program and the sp ecialization classes are then provided to the sp ecializer, which generates

a sp ecialized program.

Wenow identify the sp ecialization opp ortunities provided by creational, structural, and

behavioral design patterns, and present examples of sp ecialization patterns.

4.2 Creational Patterns

A creational design pattern abstracts the construction of ob jects, known as the products,

delegating parts of the instantiation pro cess to auxiliary classes. The use of a creational

pattern separates the op erations on an ob ject from the underlying representation, allowing

the representation to b e changed transparently, without aecting the rest of the program.

Nevertheless, this abstraction barrier implies that the pro duct ob jects must be accessed

using virtual calls, which blo ck optimization.

Memory allo cation and ob ject initialization are dominating factors during ob ject cre-

ation, so simply eliminating the virtual calls asso ciated with the creation pro cess is unlikely

to signicantly optimize a program. Thus, sp ecialization should also b e applied to the parts

of the program where the pro ducts are used, by sp ecializing the uses to the concrete typ e

of each pro duct. Such sp ecialization p ermits direct access to the pro duct ob jects, enabling

ordinary intra-pro cedural optimizations. However, such a sp ecialization strategy is only

worthwhile when the sp ecializer can determine how the pro ducts are manipulated after they

have b een created. Thus, a sp ecialization pattern for a can only givevery

limited information on when it is worthwhile to sp ecialize. On the p ositive side, the pro duct

is known to the sp ecializer when its creation can b e traced to a sp ecic use of a creational

pattern, so creational patterns do not obfuscate the sp ecialization pro cess.

Example: builder pattern

Figure 3 denes the sp ecialization pattern for the builder pattern. As an example of applying

the builder sp ecialization pattern, Figure 4a shows the ListBuilder interface for creating

AbstractList lists using the builder pattern. An implementation must provide the metho ds

start, which initializes the list, add, which extends the list, and getProduct, which nishes

the pro duction sequence by returning the head of the list. Also dened is the class Main

with a metho d f, which uses the ListBuilder interface to construct a list, and then accesses

the head of the list just pro duced. Figure 4b shows the concrete builder implementation

LinkedListBuilder, which pro duces linked lists of typ e LList the denitions of AbstractList

and LList are trivial, and not shown here.

The sp ecialization class of Figure 4c sp ecies that the metho d f of the class Main should b e

sp ecialized with resp ect to a sp ecic builder, namely the LinkedListBuilder implementation.

RR n3853

12 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

Name: Builder pattern

Description: The builder pattern allows a complex structure to b e created byinvoking a se-

quence of metho ds dened in a generic builder interface. The use of this pattern separates

the construction pro cess from the underlying representation.

Extent: Sp ecialization is applied to a collection of classes implementing the concrete represen-

tation of a structure, a class implementing the builder interface, and a client, which builds

a structure using the generic op erations provided by the builder interface. Also any subse-

quent use of the pro duct structure.

Overhead: Separation of the typ e of the pro duct from the client means that pro duct ob jects

must b e accessed using virtual calls. For the same reason, little is known ab out the initial

state of the pro duct ob jects.

Compiler: When there is either just a single kind of builder or a single kind of pro duct, a

compiler can usually generate direct calls for accessing the metho ds of the pro duct ob ject.

Nevertheless, a compiler typically do es not make use of initialization information.

Approach: Sp ecializing the client with resp ect to a particular implementation of the builder

makes the ob jects comprising the structure directly accessible to the client. Accesses to the

comp onents of the structure can then b e implemented using direct calls to the metho ds of

these ob jects. Information ab out the current state of these ob jects can b e used for further

optimizations.

Condition: The typ e of the builder must b e known to the sp ecializer p ossibly as a sp ecialization

class invariant. To guarantee sp ecialization of the builder, the sequence of building actions

must b e xed within the program. Furthermore, to guarantee direct use of the pro ducts

and that information ab out their state is exploited by the sp ecializer, they must b e used in

a xed way.

Sp ecialization class: The sp ecialization class should x the typ e of the builder, and sp ecify

sp ecialization of a metho d that b oth uses the builder and the resulting pro duct ob jects.

Applicability: High when the sp ecialization class can b e placed prop erly and the pro duct ob jects

are used often. Low to none otherwise.

Example: See Figure 4 and explanation in text.

Figure 3: Builder sp ecialization pattern

In the sp ecialized program Figure 4d, virtual calls have b een replaced by direct data-

3

structure manipulations. Sp ecialization rst replaces the virtual calls through the List-

Builder interface by direct calls, and then inlines the metho d denitions into the caller,

eliminating temp orary variables when appropriate.

Sp ecialization to a single concrete implementation p ermits the pro duct ob jects to be

accessed directly as long as they are not manipulated in a dynamic way. In the example,

3

As is the case for all of the examples shown in this pap er, the sp ecialized co de has b een resugared for

readability. INRIA

Specialization Patterns 13

class LinkedListBuilder

interface ListBuilder {

implements ListBuilder {

void start;

LList head, c;

void add Object o ;

void start {

AbstractList getProduct;

head = new LListnull;

}

c = head;

class Main {

}

ListBuilder b;

void add Object x  {

void f {

c.next = new LListx;

b.start;

c = c.next;

b.add"x";

}

b.addnew Vector;

AbstractList getProduct {

AbstractList p = b.getProduct;

return head.next;

something p.getElm ;

}

}

}

}

a Use of builder through interface b Concrete builder for linked lists

void f_LinkedListBuilder {

LinkedListBuilder b;

b.head = new LListnull;

b.c = b.head;

specclass Main_LL

b.c.next = new LList"x";

specializes Main {

b.c = b.c.next;

LinkedListBuilder b;

b.c.next =

f;

new LListnew Vector;

}

b.c = b.c.next;

AbstractList p = b.head.next;

something p.elm ;

}

c Declaration of sp ecialization to the d Result of sp ecialization

LinkedListBuilder builder

Figure 4: Sp ecializing a use of the builder pattern.

the pro duct is used in a xed way, and the virtual call to getElm has b een replaced by

its concrete denition in the LList class. If desired, the metho d something can also be

sp ecialized, adapting it to the concrete value stored in the rst elementofthe LList ob ject.

Had the pro duct b een manipulated in a dynamic way, the b enets of sp ecialization would

have b een negligible.

Other creational patterns

In addition to the builder pattern, the abstract factory and prototyp e patterns also hide

the typ es of the ob jects that they pro duce; thus, uses of these patterns are good targets

for sp ecialization. But as is the case for all creational patterns, whether the program will

b enet from sp ecialization dep ends on how the pro ducts are manipulated. The factory and

RR n3853

14 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

singleton patterns are much simpler, and the typ es of the ob jects that they pro duce is usually

evident. Uses of these patterns are thus easily handled by an optimizing compiler, but can

of course b e sp ecialized as well.

4.3 Structural Patterns

Structural design patterns organize relations b etween ob jects, enhancing reuse and repla-

cability. They allow the programmer to combine individual ob jects resp ecting a common

interface into comp ound ob jects that b ehave in new ways. By separating the ob jects using

interfaces, structural patterns allow the ob ject structure to b e transparently extended, and

new classes implementing the interface to b e added. This exibility implies, however, that

the comp onents must interact using virtual calls, obscuring the owofcontrol through the

ob ject structure.

A program that builds and traverses an ob ject structure can b e sp ecialized to a sp ecic

layout of this structure. Sp ecialization p ermits the ob jects of the structure to interact

directly, and all of the basic op erations on the structure to b e collected in a single place. If the

structure is not mo died after its creation, the metho ds that manipulate it can b e directly

sp ecialized to its layout. More generally, sp ecialization classes can be used to describ e

layouts that are of interest. As always, sp ecialization classes intro duce overheads, so the

latter approach might not b e b enecial if the structure changes to o often, or if the amount

of computation within the structure is to o limited. Sp ecialization of a

can generate co de having size prop ortional to the size of the ob ject structure. Thus, when a

structure may b e prohibitively large, sp ecialization should b e applied with caution to avoid

co de explosion.

Example: bridge pattern

Figure 5 denes the sp ecialization pattern for the bridge pattern. As an example of ap-

plying the bridge sp ecialization pattern, Figure 6a shows a use of the bridge pattern. The

class Complex represents complex numb ers, with the sp ecic implementation deferred to a

ComplexImpl ob ject. The multiply op eration is delegated to the concrete implementation,

whereas the square op eration is dened in the interface ob ject. The function f of the class

SquareFn simply computes the square of a complex numb er. Two concrete implementations

of ComplexImpl are given in Figure 6b: the RectComp implementation uses rectangular co-

ordinates to represent complex numb ers, whereas the PolarComp implementation uses p olar

co ordinates.

The sp ecialization class SquareFn_RectComplex Figure 6c sp ecies that f should b e sp e-

cialized to complex numb ers that fulll the invariants given in the Rectangular sp ecialization

class. This sp ecialization class sp ecies that the implementation ob ject has typ e RectComp.

The result of sp ecialization is an implementation of f where the complex numb ers are ac-

cessed directly, allowing the mathematical op erations to be applied directly to the ob ject

elds. Sp ecialization rst replaces virtual calls from f to the bridge interface ob ject by di-

rect calls, and similarly replaces virtual calls from the interface ob ject to the implementation INRIA

Specialization Patterns 15

Name: Bridge pattern

Description: The bridge pattern separates an ob ject into a generic interface ob ject and an

implementation ob ject. The client accesses the ob ject via the generic interface ob ject, which

provides access to a sp ecic implementation ob ject using delegation. The bridge pattern

decouples an abstraction from its implementation, so that the two can vary indep endently.

Extent: Sp ecialization is applied to an interface ob ject which has op erations that are dened in

terms of generic op erations on an implementation ob ject.

Overhead: To allow the implementation to vary indep endently from the generic interface ob ject,

metho d invo cations from the generic interface ob ject to the implementation ob ject are

implemented using virtual calls. Furthermore, the client typically requires access to the

metho ds of the implementation ob ject, which implies two levels of metho d invo cation rst

a call to the interface ob ject, then the subsequent call to the implementation ob ject.

Compiler: Since there normally is a hierarchy of implementation classes, a compiler can rarely

eliminate the virtual call from the interface ob ject to the implementation ob ject.

Approach: When the comp onents connected by the bridge are known, the bridge can often b e

eliminated. This allows direct access from the interface ob ject to the implementation ob ject.

Condition: If the coupling b etween the interface ob ject and the implementation ob ject never

changes or only changes in a xed way, then it can b e sp ecialized to remove one level of

indirection. If the interface ob ject is used by the program in a xed way, then the interface

indirection can b e sp ecialized awayaswell.

Sp ecialization class: The sp ecialization class should at least x the typ e of the implementation

ob ject, and should ideally sp ecify sp ecialization of a metho d the uses the interface ob ject

several times. Alternatively, when a single metho d in the interface ob ject calls is imple-

mented using several metho ds in the implementation ob ject, the sp ecialization class can

sp ecify sp ecialization of the interface ob ject.

Applicability: Medium when the sp ecialization class can b e placed prop erly or when there are

many calls from the interface to the implementation ob ject. Low otherwise.

Example: See Figure 6 and explanation in text.

Figure 5: Bridge sp ecialization pattern

ob ject by direct calls. These direct calls are inlined, eliminating temp orary variables when

appropriate, to pro duce the sp ecialized implementation of f shown in Figure 6d.

Other structural patterns

As is the case for the bridge pattern, the adapter, comp osite, decorator, facade, and proxy

structural patterns allow the building of structures from ob jects hidden b ehind generic

interfaces, so uses of these patterns are go o d targets for sp ecialization, and sp ecialization is

guaranteed to simplify the program when the structure do es not change or when it can b e

RR n3853

16 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

interface ComplexImpl {

void mult Complex c ;

class RectComp

double r;

implements ComplexImpl {

double i;

double r, i;

}

void mult Complex c  {

class Complex {

double cr = c.r;

ComplexImpl imp;

double ci = c.i;

void multiply Complex c  {

double nr = r*cr - i*ci;

imp.mult c ;

double ni = r*ci + i*cr;

}

r = nr; i = ci;

void square {

}

imp.mult this ;

double r { return r; }

}

double i { return i; }

double r { return imp.r; }

}

double i { return imp.i; }

class PolarComp

}

implements ComplexImpl {

class SquareFn {

...polar coordinates...

void f Complex x  {

}

x.square;

}

}

b Sp ecic numb er implementations a Generic number interface and use

speclass SquareFn_RectComplex

void f_RectComplex Complex x  {

specializes SquareFn {

RectComp tmp = x.imp;

void f Complex x ,

double cr = x.imp.r;

Rectangular x;

double ci = x.imp.i;

}

double nr = tmp.r*cr - tmp.i*ci;

specclass Rectangular

double ni = tmp.r*ci + tmp.i*cr;

specializes Complex {

tmp.r = nr; tmp.i = ni;

RectComp imp;

}

}

c Declaration of sp ecialization to the d Result of sp ecialization

NormalNum implementation

Figure 6: Sp ecializing a use of the bridge pattern.

encapsulated using sp ecialization classes. The yweight pattern optimizes memory usage by

sharing ob jects, and cannot b e sp ecialized in anyobvious way.

4.4 Behavioral Patterns

Behavioral patterns abstract over the control ow, providing generic ways of parameterizing

b ehavior. They oer a clean separation between dierent asp ects of an overall b ehavior,

making it p ossible to construct new b ehaviors by comp osing individual ob jects or classes. INRIA

Specialization Patterns 17

The overall b ehavior is distributed among co op erating ob jects, and can be mo died by

changing the way ob jects are comp osed together. Every time the collab orating ob jects that

implementabehavior are used for a sp ecic function, they must interact with each other

using virtual calls.

A program using a b ehavioral pattern can b e sp ecialized to a sp ecic b ehavior, by sp ec-

ifying the values and ob jects that control the b ehavioral pattern. Sp ecialization transforms

the complete description of the b ehavior into a single unit. Nevertheless, the b ehavioral

design patterns are so diverse that it is only for sp ecic patterns that we can guarantee

b enets from sp ecialization. Dep ending on the sp ecic pattern in question, sp ecialization

can b e done by sp ecializing the pattern use to the ob ject structure that it pro cesses, and

p ossibly to anyvalues that control how it pro cesses the ob ject structure. In any case, if the

ob jects that makeup the use of the pattern are cannot be determined by the sp ecializer,

the b ehavioral pattern cannot in general b e sp ecialized.

Example: strategy pattern

Figure 7 denes the sp ecialization pattern for the strategy pattern. As an example of its

application, Figure 8a shows a use of the strategy pattern. The Image class represents

an image using pixels dened by the RGB class. The process metho d of an Image ob ject

applies the pixelwise pro cessing strategy stored in the eld op to each the pixel of the image.

Figure 8b denes two such single-pixel op erations: Scale, which scales a pixel thereby

changing its brightness, and RedOnly, which discards all but the red comp onent.

The sp ecialization class ScaleByTwoProcess Figure 8c declares that the op eration is a

Scale op eration, and that the scaling value is 2:0. We thus sp ecialize the Image class to

a strategy that is sp ecied not only in terms of its typ e, but also in terms of its internal

state. Sp ecialization merges the eect of the strategy ob ject into the original process metho d

Figure 8d, by eliminating the virtual call to the strategy metho d, inlining the call, and

propagating the known scaling value.

Other b ehavioral patterns

As is the case for the strategy pattern, precise sp ecialization patterns can b e given to the

chain of resp onsibility,interpreter, mediator, observer, state, and visitor patterns. For the

interpreter and visitor patterns, sp ecialization is b enecial when the use of the pattern can

b e sp ecialized with resp ect to the structure pro cessed by the pattern, in which case the use

of the pattern can be completely eliminated. The command and iterator design patterns

represent opp ortunities for sp ecialization, but it is dicult to precisely sp ecify when this is

the case, except for the most basic case where the b ehavior is obtains genericity through

inheritance, and can easily b e handled by an optimizing compiler. The

externalizes the state of an ob ject, and cannot b e sp ecialized in anyobvious way.

RR n3853

18 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

Name: Strategy pattern

Description: The strategy pattern allows clients to transparently replace one algorithm by an-

other. This design pattern allows clients to cho ose among whole families of algorithms

rather than just a single algorithm.

Extent: Sp ecialization is applied to a family of algorithms all implementing the same abstract

interface, and a client that uses such algorithms through this abstract interface.

Overhead: All op erations provided by the algorithm must be accessed through the abstract

interface. The less computation is done by the algorithm, the more this overhead is b ecomes

noticeable.

Compiler: Unless the strategy is chosen explicitly b efore it is used, a compiler is unlikely to

bypass the abstract interface.

Approach: By sp ecializing the client to the concrete algorithm, the abstract interface can b e

bypassed, and the algorithm can b e inlined into the client. This op ens opp ortunities for

further sp ecialization and optimization of the algorithm to the context in which it is b eing

used.

Condition: If the coupling b etween the client and the concrete strategy b eing used never changes,

then the client can b e sp ecialized to this strategy. If the coupling do es not change during

the invo cation of a metho d in the client, the sp ecialization classes can intro duce a lo cal

invariant, allowing this metho d to b e sp ecialized to the strategy. If changes in the coupling

are completely xed then the client is guaranteed to b e sp ecializable to the strategy.

Sp ecialization class: The sp ecialization class should x the typ e of the strategy, and sp ecify

sp ecialization of a metho d that applies the strategy.

Applicability: High when the strategy is used inside a lo op, medium when used a few times,

low when used only once.

Example: See Figure 8 and explanation in text.

Figure 7: Strategy sp ecialization pattern

5 A Complete Example

To illustrate the combined eects of sp ecialization of several design patterns, we provide a

complete example: a graphical application. We rst describ e the example, fo cusing on the

to olkit used to write the application, and then characterize the overheads present in the

application and explain how they can b e eliminated.

5.1 Description

Our example is a graphical text editor application written using an abstract windowing

to olkit, styled after the Java JDK 1:1 AWT abstract windowing to olkit. Graphical win- INRIA

Specialization Patterns 19

interface RGBOP {

void handle RGB pixel ;

class Scale implements RGBOP {

}

double s;

class RGB { double r, g, b; }

void handle RGB p  {

class Image {

p.r*=s;p.g*=s;p.b*=s;

RGB [][]img; int w, h;

}

RGBOP op;

}

void process {

class RedOnly implements RGBOP {

forint i=0; i

void handle RGB p  {

forint j=0; j

p.g=0;p.b=0;

op.handleimg[i][j];

}

}

}

...

}

a RGB Image which uses op erator b RGB pixel op erations

specclass ScaleByTwoProcess

void process_ScaleByTwo {

specializes Image {

forint i=0; i

ScaleByTwo op;

forint j=0; j

void process;

RGB p = img[i][j];

}

p.r*=2.0;p.g*=2.0;p.b*=2.0;

specclass ScaleByTwo

}

specializes Scale {

}

s == 2.0;

}

c Declaration of sp ecialization to the d Result of sp ecialization

Scale op eration

Figure 8: Sp ecializing a use of the strategy pattern.

dowing to olkits often contain many opp ortunities for sp ecialization, and the JDK 1:1 AWT

4

is no exception.

We fo cus on the following uses of design patterns in the to olkit:

 The structural pattern composite is central to most graphical to olkits, allowing graphi-

cal widgets and widget containers to b e freely combined. To use the comp osite pattern,

each graphical widget and container extends an abstract class, Component the name

used in JDK 1:1.

 To allow our to olkit to function with any concrete windowing environment, we separate

each comp onentinto its general representation and its system-sp ecic peer, using the

bridge pattern Section 4.3. The p eer ob jects are created using the abstract factory

creational pattern, which denes a general interface for creating p eers. To use the

4

The JFC Swing library contains even more opp ortunities for sp ecialization, but the standard JDK 1:1

AWT is sucient for this example.

RR n3853

20 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

extends Window implements Component references Panel Label Button Text Container Button Button Button Button Button

Window Panel Text

LabelPeer ButtonPeer TextPeer WindowPeer PanelPeer Panel Label Text

XLabelPeer XButtonPeer XTextPeer XWindowPeer XPanelPeer

a Class hierarchy b Structure of the application

Figure 9: Overview of graphical application.

abstract factory, we let a central class named Toolkit in JDK 1:1 function as an

interface for instantiating p eers.

 To simplify event handling, we use the observer b ehavioral pattern for which there

are standard interfaces in JDK 1:1. Clients subscrib e to events generated by sp e-

cic widget ob jects, such as buttons, and are notied when these events o ccur using

standard Java metho d calls.

The class hierarchy of the basic graphical ob jects of the to olkit is shown in Figure 9a.

When launched, the text editor initializes itself, arranging its graphical app earance il-

lustrated in Figure 9b, and then waits for input events to b e generated by the user, each

event triggering a sp ecic action.

5.2 Overheads

Each use of a design pattern in the graphical to olkit gives rise to a sp ecic overhead. The

use of the comp osite pattern makes it p ossible to change the graphical app earance of the

program at run time. A virtual metho d such as repaint, that is implemented by all the

Component ob jects, must use virtual calls to traverse the comp osite structure. Furthermore,

the use of the abstract factory together with the bridge hides the typ es of the p eer ob jects,

in principle allowing new p eers to be intro duced at any p oint; all calls from a Component

ob ject to its native implementation are virtual. Finally,every time an event is generated,

a corresp onding event ob ject is created and passed to the observers currently subscrib ed to

this event. Each observer insp ects the event and acts accordingly.

Figure 10a shows the call graph of invoking the repaint metho d on the top-level win-

dow ob ject. The ob ject structure is traversed, using virtual calls to propagate the repaint

op eration to all the p eer ob jects. INRIA

Specialization Patterns 21

interface Window class Window

class direct call virtual call

Panel Panel

Button Button Button Text Label Text

Button Button

WindowPeer XWindowPeer PanelPeer XPanelPeer

XButtonPeer XLabelPeer XPanelPeer ButtonPeer ButtonPeer ButtonPeer LabelPeer PanelPeer XButtonPeer XButtonPeer

TextPeer XButtonPeer XTextPeer XTextPeer

ButtonPeer ButtonPeer TextPeer XButtonPeer

b After sp ecialization

a Before sp ecialization

Figure 10: Call graph of repaint, b efore and after sp ecialization.

5.3 Sp ecialization

First, the application is sp ecialized to the way the comp osite ob jects are comp osed. The

repaint metho d of the ro ot Window ob ject can thus refresh the entire application at once,

without traversing the widget structure. Next, the application is sp ecialized to the concrete

p eer ob jects b eing used. This transformation allows comp osite ob jects to directly manipulate

their p eer ob jects. Finally, the application is sp ecialized to the concrete observer/observee

relations of the application. An eventnow results in the actions that it implies b eing directly

p erformed throughout the application.

Figure 10b shows the call graph of invoking the repaint metho d after sp ecializing for

the widget structure and a sp ecic set of p eers. Calls are made directly to the p eer ob jects,

without traversing the ob ject structure.

A more complex application might manipulate its graphical app earance while running.

However, suchan application would often be divided into several indep endent units, that

are congured individually. Sp ecialization can b e applied separately to each such unit.

6 Assessment

Program sp ecialization is applicable when design patterns are not used in their full gen-

erality. Design patterns allow the same program parts to be used to implement dierent

functionalities. Sp ecialization can optimize such program parts when the exact function-

ality is xed, either b ecause it is explicit in the program or b ecause it is made so using

sp ecialization classes.

On the contrary, those uses of design patterns whose features are completely exploited are

not suitable for sp ecialization. Highly dynamic programs that often recongure themselves

are easy to write using design patterns, but are dicult to sp ecialize. Sp ecialization classes

are only useful here when a xed implementation can be selected outside of the critical

regions of the program, since there is an overhead asso ciated with switching b etween sp e-

RR n3853

22 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

JDK 1.2 JIT HotSp ot

Benchmark Normal Sp ec. Sp eedup Normal Sp ec. Sp eedup

Bridge mandelbrot 2.582 2.583 1.00 6.458 5.682 1.14

Builder matrix 4.654 3.778 1.23 4.988 2.613 1.91

Strategy image 3.298 1.626 2.03 2.283 0.768 2.97

Iterator memb er 6.132 5.114 1.20 6.227 3.409 1.83

Table 1: Benchmark results real time, in seconds

cialized implementations. Knowledge of the degree of adaptability asso ciated with each use

of a design pattern is thus essential for using sp ecialization patterns to optimize a program.

To illustrate the p erformance b enets of eliminating uses of design patterns by sp ecial-

ization, we consider a few b enchmarks, based on the examples of Section 4. In practice,

however, the improvement due to sp ecialization can vary widely, dep ending on the number

of sp ecialization opp ortunities intro duced by eliminating the abstraction barriers created by

the use of design patterns.

For b enchmarks, we use the builder design pattern to build matrices with sparse and

dense underlying representations, the bridge design pattern to compute the Mandelbrot set

using complex numb er arithmetic, and nally the strategy pattern to p erform a number of

dierent image pro cessing tasks. In addition, the iterator example from Sections 1 and 3.3

is used to implementvarious set op erations. The b enchmarks have b een done using Sun's

JDK 1.2.1 JIT and HotSp ot compilers on a 300MHz UltraSparc, ignoring the rst iteration

of each b enchmark to minimize cache eects and ensure that all dynamic optimization is

complete. The results are shown in Table 1.

The sp eedup due to sp ecialization varies with the complexity of the adaptation taking

place in the b enchmark. The bridge b enchmark only has a few, simple p oints of adaptation

and is dominated bynumerical computation, so the b enet due to simply sp ecializing away

the bridge ranges from non-existentto minor. The iterator and builder b enchmarks have

more p oints of adaptation, and so they b enet more from sp ecialization. Last, the strategy

b enchmark has a single but critical p oint of adaptation, that can b e completely eliminated

using sp ecialization, which greatly simplies the program control ow.

7 Related Work

Program rewriting techniques can b e used in place of program sp ecialization to map uses

of design patterns into ecient implementations, as shown byTurwé and De Meuter [30].

Here, a program transformation engine based on Prolog rewriting rules is used to p erform

architectural transformations b efore compilation. While their optimization technique is very

dierent from partial evaluation, their overall approach can b e unied with sp ecialization INRIA

Specialization Patterns 23

patterns: for each design pattern, a sp ecialization pattern can describ e what rewriting rules

give the b est optimizations.

Templates in C++ allow the programmer to express static information ab out typ es and

simple values, thus providing more information to the compiler. The information can be

used to x typ es in the program, and even to p erform simple partial evaluation of integral

values [31]. For example, rather than implementing the strategy pattern with a virtual

call, the choice of strategy can by statically xed using templates [16]. However, templates

sp ecialize on a class-by-class bases, and cannot sp ecialize for the way ob jects are comp osed

together, except when this is done statically in the program. In addition, explicit syntax is

needed to express prop erties using templates, and source co de must b e manually duplicated

to retain the generic b ehavior.

Many compilation systems implement generally applicable optimizations similar to those

p erformed p erformed by program sp ecialization, but without requiring user guidance. To

reduce the complexity of p erforming analysis, simplied typ e inference algorithms suchas

Class Hierarchy Analysis are used [12], combined with prole information that guides sp ec-

ulative optimizations such as receiver-prediction [18, 20]. Since techniques such as inlining

and sp ecialization for typ es customization [7] and metho d argument sp ecialization[10] can

cause co de explosion, the same proling information is used to fo cus these optimizations on

the critical parts of the program [11,20]. The optimizations oered by such systems dep end

on the accuracy of the analyses and proling system. As a result, the level of optimization

is dicult to predict, and structural overheads are not easily detected. By contrast, sp e-

cialization is parameterized by information provided by the programmer, and can pro duce

source co de that can b e manually insp ected for remaining ineciencies b efore b eing shipp ed

as a complete pro duct.

Software architectures oer a global approach to organizing programs, byworking within

a framework [29]. A program written using a software architecture uses a generic infras-

tructure, which supp orts mechanisms to oer extensibility and mo dularity. However, there

is a fundamental dierence between design patterns and software architectures. A design

pattern describ es a design idea without b eing limited to a single, concrete implementation,

whereas a software architecture gives a concrete implementation of an infrastructure without

sp ecifying the comp onents that can b e integrated to form a complete application. Marlet

et al. have shown program sp ecialization to be an eective to ol for eliminating the archi-

tectural overheads of software architectures, automatically transforming a program written

using a software architecture into an ecient implementation [24]. Since there is a concrete

implementation for a given software architecture, sp ecialization can b e applied to a program

written using this software architecture, without requiring guidance from the user.

8 Future Work

In this pap er we have shown that a given design pattern provides enough structure to a

program to systematically enable its optimization using program sp ecialization. However,

intertwining many design patterns may aect the sp ecialization opp ortunities of the resulting

RR n3853

24 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

program. To address this issue we are studying how the comp osition of design patterns

impacts sp ecialization opp ortunities, and are characterizing sp ecialization patterns resulting

from design pattern comp ositions.

The Java Beans framework is dened using standard Java constructs under certain con-

straints. Just like a given framework systematically intro duces sp ecic overheads, the Java

Beans comp onent architecture also intro duces overheads into programs. Sp ecialization can

b e automatically applied to optimize away these overheads. For example, the standard Java

Beans event mo del can be sp ecialized with an overall eect similar to the sp ecialization

of the strategy design pattern Section 4.4. Concretely, we aim to completely automate

the sp ecialization pro cess for the sp ecic case of Java Beans, by automatically generating

sp ecialization classes.

With a more formal denition of design patterns, it is p ossible that user guidance of the

sp ecialization pro cess could b e greatly simplied. For example, if the source language had

supp ort for design patterns [5, 19,21] or if the program were develop ed using a CASE to ol

that supp orts design patterns [25], sp ecialization classes could b e automatically generated

for each use of a design pattern. These sp ecialization classes would then precisely dene the

sp ecialization capabilities of the resulting program.

9 Conclusion

Design patterns fo cus on how programs should b e structured to oer features suchasmodu-

larity and extensibility. However, this structuring is directly mapp ed into an implementation;

features are directly implemented in terms of mechanisms that cause overheads at run time.

Still, these overheads are predictable since they are inherent to each design pattern.

This pap er intro duces sp ecialization patterns: an approach aimed at optimizing patterns

of overheads identied in design patterns. This optimization pro cess, based on program sp e-

cialization, removes abstraction layers by exploiting information ab out ob ject comp osition.

Wehave demonstrated the applicability of our approach to several kinds of design pat-

terns creational, structural, and b ehavioral. For each kind of design pattern, we have

characterized sp ecialization opp ortunities. Examples have b een used to concretely show the

eectiveness of program sp ecialization in removing the overheads inherent to design patterns.

In eect, wehave shown that program sp ecialization can b e used systematically to map

programs develop ed using design patterns into ecient implementations. This mapping

is guided by information provided by design patterns. As a result, we have extended the

scop e of design patterns: not only do they guide program development, but they also enable

systematic optimization of the resulting programs.

Acknowledgements

We would like to thank Phillip e Boinot, Aino Cornils, and Gilles Muller for their helpful

comments on this pap er. Wewould also like to thank Miguel A. de Miguel and Peter Chang

for timely completion of a prototyp e implementation of the C to Java translator INRIA

Specialization Patterns 25

class Array implements MinimalCollection {

Object []elements;

int size;

Arrayint size {

this.size = size;

this.elements = new Object[size];

}

public Object getint n { return elements[n]; }

public int getSize { return size; }

Iterator iterator {

return new ArrayIterator this ;

}

...other methods for implementing the MinimalCollection interface...

}

class ArrayIterator implements Iterator {

Array array;

int current, max;

ArrayIterator Array a  {

this.array = a;

this.current = 0;

this.max = a.getSize;

}

boolean hasNext { return current

Object next { return array.getcurrent++; }

}

Figure 11: Relevant parts of Array and its iterator ArrayIterator.

A Iterator Example Implementation

Figure 11 shows those parts of the Array and ArrayIterator classes that are relevanttothe

iterator example shown in the intro duction.

References

[1] G. Aigner and U. Hölzle. Eliminating virtual function calls in C++ programs. In

Proceedings of the European Conference on Object-orientedProgramming ECOOP'96,

volume 1098 of Lecture Notes in Computer Science, pages 142166, Lisb on, Portugal,

June 1996. Springer.

RR n3853

26 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

[2] L.O. Andersen. Program Analysis and Specialization for the C Programming Lan-

guage. PhD thesis, Computer Science Department, University of Cop enhagen, May

1994. DIKU Technical Rep ort 94/19.

[3] R. Baier, R. Glück, and R. Zöchling. Partial evaluation of numerical programs in

Fortran. In ACM SIGPLAN Workshop on Partial Evaluation and Semantics-Based

Program Manipulation, pages 119132, Orlando, FL, USA, June 1994. Technical Rep ort

94/9, University of Melb ourne, Australia.

[4] A. Bondorf. Self-Applicable Partial Evaluation. PhD thesis, DIKU, University of Cop en-

hagen, Denmark, 1990. Revised version: DIKU Rep ort 90/17.

[5] J. Bosch. Design patterns as language constructs. Journal of Object-OrientedProgram-

ming,Novemb er 1996.

[6] B. Calder and D. Grunwald. Reducing indirect function call overhead in C++ programs.

In Conference Record of the Twentieth Annual ACM SIGPLAN-SIGACT Symposium

on Principles Of Programming Languages, pages 397408. ACM Press, 1994.

[7] C. Chamb ers and D. Ungar. Customization: Optimizing compiler technology for SELF,

A dynamically-typ ed ob ject-oriented programming language. In Bruce Knob e, editor,

Proceedings of the SIGPLAN '89 Conference on Programming Language Design and

Implementation SIGPLAN '89, pages 146160, Portland, OR, USA, June 1989. ACM

Press.

[8] C. Consel. A tour of Schism: a partial evaluation system for higher-order applicative

languages. In Partial Evaluation and Semantics-Based Program Manipulation, pages

6677, Cop enhagen, Denmark, June 1993. ACM Press.

[9] C. Consel, L. Hornof, F. Noël, J. Noyé, and E.N. Volanschi. A uniform approach for

compile-time and run-time sp ecialization. In O. Danvy, R. Glück, and P. Thiemann,

editors, Partial Evaluation, International Seminar, Dagstuhl Castle, number 1110 in

Lecture Notes in Computer Science, pages 5472, February 1996.

[10] J. Dean, C. Chamb ers, and D. Grove. Selective sp ecialization for ob ject-oriented lan-

guages. ACM SIGPLAN Notices, 306:93102, June 1995.

[11] J. Dean, G. DeFouw, D. Grove, V. Litvinov, and C. Chamb ers. Vortex: an optimizing

compiler for ob ject-oriented languages. In OOPSLA' 96 Conference, pages 93100, San

Jose CA, Octob er 1996.

[12] J. Dean, D. Grove, and C. Chamb ers. Optimization of ob ject-oriented programs using

static class hierarchy analysis. In Proceedings of ECOOP'95, Aarhus, Denmark, August

1995. Springer-Verlag.

[13] D. Detlefs and O. Agesen. Inlining of virtual metho ds. In ECOOP'99 [15], pages

258278. INRIA

Specialization Patterns 27

[14] K. Driesen and U. Hölzle. The direct cost of virtual function calls in C++. In OOP-

SLA'96 ConferenceProceedings,volume 31, 10 of ACM SIGPLAN Notices, pages 306

323, New York, Octob er610 1996. ACM Press.

[15] Proceedings of the European Conference on Object-orientedProgramming ECOOP'99,

volume 1628 of Lecture Notes in Computer Science, Lisb on, Portugal, June 1999.

[16] E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns: Elements of

Reusable Object-Oriented Software. Addison-Wesley, 1994.

[17] D. Grove, J. Dean, C. Garrett, and C. Chamb ers. Prole-guided receiver class predic-

tion. In OOPSLA'95 ConferenceProceedings,volume 30, 10, pages 108123, New York,

Octob er 1995. ACM Press.

[18] D. Grove, J. Dean, C. Garrett, and C. Chamb ers. Prole-guided receiver class predic-

tion. In Proceedings of OOPSLA '95, pages 108123, Austin, TX, Octob er 1995.

[19] G. Hedin. Language supp ort for design patterns using attribute extension. In J. Bosch

and S. Mitchell, editors, ECOOP'97 Workshop Reader, volume 1357 of Lecture Notes

in Computer Science, pages 137140. Springer-Verlag, June 1998.

[20] U. Hölzle and D. Ungar. Optimizing dynamically-dispatched calls with run-time typ e

feedback. In Proceedings of the Conference on Programming Language Design and

Implementation, pages 326336, New York, NY, USA, June 1994. ACM Press.

[21] S. Krishnamurthi, Y. Erlich, and M. Felleisen. Expressing structural prop erties as

language constructs. In S.D. Swierstra, editor, Programming Languages and Systems,

8th European Symposium on Programming ESOP'99, volume 1576 of Lecture Notes

in Computer Science, pages 258272. Springer-Verlag, 1999.

[22] J.L. Lawall and G. Muller. Ecient incremental checkp ointing of Java programs. Re-

search Rep ort 3810, INRIA, Rennes, France, Novemb er 1999.

[23] J.W. Lloyd and J.C. Shepherdson. Partial evaluation in logic programming. Journal of

Logic Programming, 11:217242, 1991.

[24] R. Marlet, S. Thibault, and C. Consel. Mapping software architectures to ecient imple-

mentations via partial evaluation. In ConferenceonAutomated Software Engineering,

pages 183192, LakeTaho e, Nevada, Novemb er 1997. IEEE Computer So ciety.

[25] T.D. Meijler, S. Demeyer, and R. Engel. Making design patterns explicit in FACE, a

framework adaptive comp osition environment. In M. Jazayeri and H. Schauer, editors,

Proceedings ESEC/FSE '97,volume 1301 of Lecture Notes in Computer Science, pages

94110. Springer-Verlag, Septemb er 1997.

[26] G. Muller and U. Schultz. Harissa: A hybrid approach to Java execution. IEEE

Software, pages 4451, March 1999.

RR n3853

28 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel

[27] J. Plevyak and A. A. Chien. Precise concrete typ e inference for ob ject-oriented lan-

guages. In OOPSLA '94 Conference Proceedings,volume 29:10 of SIGPLAN Notices,

pages 324324. ACM, Octob er 1994.

[28] U. Schultz, J. Lawall, C. Consel, and G. Muller. Towards automatic sp ecialization of

Java programs. In ECOOP'99 [15], pages 367390.

[29] M. Shaw and D. Garlan. SoftwareArchitecture. Prentice Hall, 1996.

[30] T. Tourwe and W. De Meuter. Optimizing ob ject-oriented languages through architec-

tural transformations. Lecture Notes in Computer Science, 1575:244258, 1999.

[31] T. L. Veldhuizen. C++ templates as partial evaluation. In ACM SIGPLAN Workshop

on Partial Evaluation and Semantics-Based Program Manipulation, pages 1318, San

Antonio, TX, USA, January 1999. ACM Press.

[32] E.N. Volanschi, C. Consel, G. Muller, and C. Cowan. Declarative sp ecialization of

ob ject-oriented programs. In OOPSLA'97 ConferenceProceedings, pages 286300, At-

lanta, USA, Octob er 1997. ACM Press. INRIA Unité de recherche INRIA Lorraine, Technopôle de Nancy-Brabois, Campus scientifique, 615 rue du Jardin Botanique, BP 101, 54600 VILLERS LÈS NANCY Unité de recherche INRIA Rennes, Irisa, Campus universitaire de Beaulieu, 35042 RENNES Cedex Unité de recherche INRIA Rhône-Alpes, 655, avenue de l’Europe, 38330 MONTBONNOT ST MARTIN Unité de recherche INRIA Rocquencourt, Domaine de Voluceau, Rocquencourt, BP 105, 78153 LE CHESNAY Cedex Unité de recherche INRIA Sophia-Antipolis, 2004 route des Lucioles, BP 93, 06902 SOPHIA-ANTIPOLIS Cedex

Éditeur

INRIA, Domaine de Voluceau, Rocquencourt, BP 105, 78153 LE CHESNAY Cedex (France) http://www.inria.fr ISSN 0249-6399