Category Archives: 转载

这篇文章主要介绍了一下String、StringBuffer对象在初始化和字符串连接时的优化,很不错。

——

This topic illustrates the performance improvement techniques in String and StringBuffer with the following sections:

Overview of String and StringBuffer

Immutable objects cannot be modified once they are created. Mutable objects can be modified after their creation. String objects are immutable where as StringBuffer objects are mutable.
You need to carefully choose between these two objects depending on the situation for better performance. The following topics illustrate in detail :

Note: This section assumes that reader has some basic knowledge of Java Strings and StringBuffer.

Better way of creating Strings

You can create String objects in the following ways.

 

Which of the above gives better performance?

Here is a code snippet to measure the difference.

StringTest1.java

The output of this code

 

It clearly shows first type of creation is much more faster than second type of creation. Why?

Because the content is same s1 and s2 refer to the same object where as s3 and s4 do not refer to the same object. The ‘new’ key word creates new objects for s3 and s4 which is expensive.

 

How the JVM works with Strings:

Java Virtual Machine maintains an internal list of references for interned Strings ( pool of unique Strings) to avoid duplicate String objects in heap memory. Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it  does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object which it creates through ‘new’ keyword. You can explicitly force JVM to do this type of checking for String objects which are created through ‘new’ keyword using String.intern() method. This forces JVM to check the internal list and use the existing String object if it is already present.

So the conclusion is, JVM maintains unique String objects for String literals internally. Programmers need not bother about String literals but they should bother about String objects that are created using ‘new’ keyword and they should use intern() method to avoid duplicate String objects in heap memory which in turn improves java performance. see the following section for more information.

The following figure shows the creation of String Objects without using the intern() method.

image002

 

You can test the above difference programmatically using == operator and String.equals() method.

== operator returns true if the references point to the same object but it does not check the contents of the String object where as String.equals() method returns true if the contents of the String objects are equal.

s1==s2 for the above code returns true because s1 and s2 references point to the same object.

s3.equals(s4) for the above code returns true because both objects content  is same which is “hello”.

You can see this mechanism in the above figure. Here, we have three separate objects which contain same content,”hello”. Actually we don’t need separate objects because they use memory and take time to execute.

How do you make sure that the String objects are not duplicated?

The next topic covers this interesting interning String mechanism.

Optimization by Interning Strings

In situations where String objects are duplicated unnecessarily, String.intern() method avoids duplicating String objects. The following figure shows how the String.intern() method works. The String.intern() method checks the object existence and if the object exists already, it changes point of reference to the original object rather than create a new object.

The following figure shows the creation of String literal and String Object using intern

image002

 

Here is the sample code to know the importance of String.intern() method..

StringTest2.java

Here is the output of the above code

Optimization techniques when Concatenating Strings

You can concatenate multiple strings using either + operator or String.concat()  or   StringBuffer.append(). Which is the best one interms of performance?

The choice depends on two scenarios,first scenario is compile time resolution versus run time resolution and second scenario is wether you are using StringBuffer or String. In general, programmers think that StringBuffer.append() is better than + operator or String.concat() method. But this assumption is not true under certain conditions.

1) First scenario: compile time resolution versus run time resolution

Look at the following code StringTest3.java and the output.

The output of this code

 

Interestingly the + operator is faster than StringBuffer.append() method. Let us see why?

Here the compiler does a good job of optimization. Compiler simply concatenates at compile time as shown below. It does compile time resolution instead of runtime resolution, this happens when you create a String object using ‘new’ key word.

before compilation:

String result = “This is”+”testing the”+”difference”+”between”+”String”+”and”+”StringBuffer”;

after compilation

String result = “This is testing the difference between String and StringBuffer”;

String object is resolved at compile time where as StringBuffer object is resolved at run time. Run time resolution takes place when the value of the string is not known in advance where as compile time resolution happens when the value of the string is known in advance. Here is an example.

Before compilation:

public String getString(String str1,String str2) {

            return str1+str2;

}

After compilation:

return new StringBuffer().append(str1).append(str2).toString();

This resolves at run time and take much more time to execute.

2) Second scenario: Using StringBuffer instead of String

If you look at the following code, you will find StringBuffer is faster than String for concatenation which is opposite to above scenario.

StringTest4.java

the output of the code is

 

It shows StringBuffer.append() is much more faster than String. Why?

The reason is both resolve at runtime but the + operator resolves in a different manner and uses String and StringBuffer to do this operation.

 

Optimization by initializing StringBuffer

You can set the initial capacity of StringBuffer using its constructor this improves performance significantly. The constructor is StringBuffer(int length), length shows the number of characters the StringBuffer can hold.

You can even set the capacity using ensureCapacity(int minimumcapacity) after creation of StringBuffer object. Initially we will look at the default behavior and then the better approach later.

The default behavior of StringBuffer:

StringBuffer maintains a character array internally.When you create StringBuffer with default constructor StringBuffer() without setting initial length, then the StringBuffer is initialized with 16 characters. The default capacity is 16 characters. When the StringBuffer reaches its maximum capacity, it will increase its size by twice the size plus 2 ( 2*old size +2).

If you use default size, initially and go on adding characters, then it increases its size by 34(2*16 +2) after it adds 16th character and it increases its size by 70(2*34+2) after it adds 34th character. Whenever it reaches its maximum capacity it has to create a new character array and recopy old and new characters. It is obviously expensive. So it is always good to initialize with proper size that gives very good performance.

I tested the above StringTest4.java again with two StringBuffers, one without initial size and other with initial size. I added 50000 ‘hello’ objects this time and did not use the + operator. I initialized the second StringBuffer with StringBuffer(250000).

The output is

It shows how effective the initialization of StringBuffer is. So it is always best to initialize the StringBuffer with proper size.

Key Points

  1. Create strings as literals instead of creating String objects using ‘new’ key word whenever possible
  2. Use String.intern() method if you want to add number of equal objects whenever you create String objects using ‘new’ key word.
  3. + operator gives best performance for String concatenation if Strings resolve at compile time
  4. StringBuffer with proper initial size gives best performance for String concatenation if Strings resolve at run time.

原文链接:http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm

人工智能标记语言 AIML Tag

v1.0.1

标签 含义 备注
<aiml> 3.2. AIML Element AIML block delimeter
<topic name=”X”> 4. Topic X is AIML pattern
<category> 5. Category AIML knowledge unit
<pattern> 6. Pattern AIML input pattern
<that> 6.1. Pattern-side That contains AIML pattern
<template> 7. Template AIML response template
<star index=”N”/> 7.1.1. Star binding of *
<that index=”M,N”/> 7.1.2. Template-side That previous bot utterance
<input index=”N”/> 7.1.3. Input input sentence
<thatstar index=”N”/> 7.1.4. Thatstar binding of * in that
<topicstar index=”N”/> 7.1.5. Topicstar binding of * in topic
<get name=”XXX”/> 7.1.6. Get Botmaster defined XXX, default
<bot name=”XXX”/> 7.1.6.1. Bot Custom bot parameter
<sr/> 7.1.7. Short-cut elements <srai><star/></srai>
<person2/> 7.1.7. Short-cut elements <person2><star/></person2;>
<person/> 7.1.7. Short-cut elements <person><star/></person;>
<gender/> 7.1.7. Short-cut elements <gender><star/></gender;>
<date/> 7.1.8. System-defined predicates date and time
<id/> 7.1.8. System-defined predicates client identifer
<size/> 7.1.8. System-defined predicates # of categories loaded
<version/> 7.1.8. System-defined predicates AIML program version
<uppercase> 7.2.1. Uppercase convert all text to Uppercase
<lowercase> 7.2.2. Lowercase convert all text to Lowercase
<formal> 7.2.3. Formal capitalize every word
<sentence> 7.2.4. Sentence capitalize the first word
<condition name=”X” value=”Y”> 7.3.1. Condition One shot branch
<condition name=”X”> 7.3.1. Condition Single predicate branch
<condition> 7.3.1. Condition Multi predicate branch
<random> 7.3.2. Random Random uniform selection
<li name=”X” value=”Y”> 7.3.1. Condition used by <condition>
<li value=”Y”> 7.3.1. Condition used by <condition>
<li> 7.3.2. Random used by <random>,<condition>
<set name=”XXX”> 7.4.1. Set May return XXX or value
<gossip> 7.4.2. Gossip Append to file
<srai> 7.5.1. SRAI Recursion
<person2> 7.6.1. Person2 swap 1st & 3rd person
<person> 7.6.2. Person swap 1st & 2nd person
<gender> 7.6.3. Gender change gender pronouns
<think> 7.7.1. Think Hides side-effects
<learn> 7.7.2. Learn AIML loading
<system> 7.8.1. System platform-dependent
<javascript> 7.8.2. JavaScript Javascript

1月份最佳字体设计Top40

虽然不是每个人都做字体设计,但字体对于设计师来说却息息相关。字体设计者Sean Mitchell 公布了1月份的最佳字体,让我们来一同欣赏一下吧:

Cultivated Mind: Amour

amour 40 Of the most beautiful typeface designs released this January

A romantic handwritten retro inspired font.

 

Sudtipos: Bellissima Script

bellissima script pro 40 Of the most beautiful typeface designs released this January

An effusive energy that appeals much beyond its sourcing.

 

The Northern Block: Neusa

neusa 40 Of the most beautiful typeface designs released this January

A condensed geometric sans serif inspired by early space explorations including the iconic Life magazine coverage of the 1969 Apollo program.

 

Emil Kozole: Attitude

attitude 40 Of the most beautiful typeface designs released this January

Inspired by Japan pop culture and American hip hop subculture.

 

Latinotype: Trend

trend 40 Of the most beautiful typeface designs released this January

A font made of layers, taking as a basis a sans and a slab font.

 

Blake E. Marquis: York

york 40 Of the most beautiful typeface designs released this January

Derived out of a graphic style using heavy shading and depth.

 

La Goupil: Insolente

insolente 40 Of the most beautiful typeface designs released this January

A versatile and realistic human script.

 

Jessica Hische: Minot

minot 40 Of the most beautiful typeface designs released this January

Comes in three styles, outline, fill, and box. Meant to be used together to create multi–color headlines.

 

HVD Fonts: Brandon Text

brandon text 40 Of the most beautiful typeface designs released this January

The companion of the famous Brandon Grotesque type family. It has a higher x–height than the Grotesque version and is optimized for long texts, small sizes and screens.

 

Letters from Sweden: Kumla

kumla 40 Of the most beautiful typeface designs released this January

Kumla is Letters from Sweden’s first release in the “Fabrik Suite” — a project inspired by Swedish industry, factories and harbors.

 

Los Andes: Moderna

moderna 40 Of the most beautiful typeface designs released this January

A modern sans serif, simple and neutral.

 

Onrepeat: Port

port 40 Of the most beautiful typeface designs released this January

An experimental Didone typeface with a modern twist.

 

A2-Type: Regular

regular 40 Of the most beautiful typeface designs released this January

Suggests a Modernist approach to design, but is open for interpretation.

 

Ahmet Altun: Halis Rounded

halis rounded 40 Of the most beautiful typeface designs released this January

Soft and eye-pleasing even though it has geometric and straight borders.

 

Insigne: Steagal

steagal 40 Of the most beautiful typeface designs released this January

Softened edges, which simulate brush strokes and retain the feeling of the human hand.

 

Grilli Type: GT Pressura

gt pressura 40 Of the most beautiful typeface designs released this January

Inspired by type stamped on shipping boxes, GT Pressura uses the visual effect of ink spreading under pressure as a stylistic device.

 

Matthew Butterick: Concourse

concourse 40 Of the most beautiful typeface designs released this January

The superbly satisfying sans serif.

 

Eurotypo: Fiesole

fiesole 40 Of the most beautiful typeface designs released this January

Inspired by calligraphic models, a bookface font family to be used for text, display and caption.

 

Ryan vs. Clark: Liberator

liberator 40 Of the most beautiful typeface designs released this January

From a bygone era, when our grandparents fought for the freedom we enjoy today. It’s bomber–inspired face provides a masculine punch to any project or design.

 

Hoftype: Capita

capita 40 Of the most beautiful typeface designs released this January

Strong in appearance, with controlled motion of the contour, vivid and warm, with gentle flow — it avoids any harshness of many slab serifs.

 

Just Another Foundry: JAF Domus Titling

jaf domus titling 40 Of the most beautiful typeface designs released this January

A rounded typeface with classical Roman proportions. It is unique in that it was designed as an all–caps sans from the beginning.

 

Alan Dague-Greene: Courier Prime

courier prime 40 Of the most beautiful typeface designs released this January

A Courier made for screenplays. It’s Courier, just better.

 

Blue Vinyl: Barmbrack

barmbrack 40 Of the most beautiful typeface designs released this January

Inspired by decorative Victorian showcard lettering.

 

Moretype: Varly

varly 40 Of the most beautiful typeface designs released this January

A single weight handwritten style font, honest and charming but still lively enough to add flare.

 

Mattox: Mathlete

mathlete 40 Of the most beautiful typeface designs released this January

A hand–drawn typeface as sweet as pi.

 

Rui Abreu: Azo Sans

azo sans 40 Of the most beautiful typeface designs released this January

A new sans serif loosely based on the elementary forms of geometry.

 

Typetanic Fonts: Columbia Titling

columbia titling 40 Of the most beautiful typeface designs released this January

Based on wide Clarendon–style wood type and industrial signage.

 

Kimmy Design: Maxwell Sans

maxwell sans 40 Of the most beautiful typeface designs released this January

A clean condensed san serif inspired by similar retro fonts from the 1950’s.

 

La Boite Graphique: Adonide

adonide 40 Of the most beautiful typeface designs released this January

A contemporary sans serif.

 

Jeremy Tankard: Capline

capline 40 Of the most beautiful typeface designs released this January

An all capital typeface with an inline detail.

 

JCFonts: Hand Gothic

hand gothic 40 Of the most beautiful typeface designs released this January

A condensed typeface with a hand–lettering feel, available in two weights.

 

Fatype: U8

u8 40 Of the most beautiful typeface designs released this JanuaryAn early modernist sans serif based on the signage of the Berlin subway system, with generous proportions, a strong character, and a clean design.

 

Glen Jan: Affect

affect 40 Of the most beautiful typeface designs released this January

A unicase display sans family.

 

Xavier Cervello: Thingbats Mono & Thingbats Life Iconset

thingbats 40 Of the most beautiful typeface designs released this January

Minimal, rounded and contemporary.

 

Stawix: Soin Sans Pro

soin sans pro 40 Of the most beautiful typeface designs released this January

Designed with geometric ratio and humanist proportions.

 

Wood Type Revival: Borders & Ornaments

borders ornaments 40 Of the most beautiful typeface designs released this January

Rugged American borders sit side–by–side with formal European patterns and DeLittle of York’s distinctive floral ornaments. Enigmatic hand–carved work from India and well–machined geometric American shapes both take their rightful place in this varied cluster of decorative designs.

 

Laura Worthington: Mandevilla

mandevilla 40 Of the most beautiful typeface designs released this January

Refined, quiet and elegant, yet quirky enough to employ slim filaments that somehow are not faint of heart, Mandevilla is named for the verdant tropical vine.

 

PintassilgoPrints: Dranskof

dranskof 40 Of the most beautiful typeface designs released this January

A light–hearted, cheery font, inspired by a page from an extraordinary Serbian publication for children by the writer, poet and journalist Duško Radović.

 

BAT: Scripto

scripto 40 Of the most beautiful typeface designs released this January

Vivid and brisk, reflecting its author’s personality.

 

Huy!Fonts: Adoquin

adoquin 40 Of the most beautiful typeface designs released this January

A functional and warm font family.

原文链接:http://thenextweb.com/dd/2013/02/02/x-of-the-most-beautiful-typeface-designs-released-this-january/