Showing posts with label Strings Experiments. Show all posts
Showing posts with label Strings Experiments. Show all posts

Sunday, November 21, 2010

String.replaceAll() vs String replaceAll code

String manipulation is one of the most commonly used aspect of programming. We do a lot of string manipulation like replacing a particular word in a string, stripping the string of unwanted words/tags, concatenating a string etc., .

It is very easy to introduce inefficiencies in the code while doing string manipulation. Programming languages provides a lot of built in API’s to manipuate a string. There is a very little chance for the built in API(s) to have inefficient code. Mostly it is the incorrect usage of API’s by us which brings in the inefficiency.

Let us take a case to illustrate this point,

Do a HTML escape for the given html document. The code should convert all the <, > , & , ‘ , ” in the string to < , > , & , ' , " respectively.

Source: Codeexperiments

Version 1:

This can be easily accomplished by using the java api String.replaceAll(String regex, String replacement). The following code does the html escaping.

String str = “

Hello World
”;
str = str.replaceAll(“<”,”<”); str = str.replaceAll(“>”,”>”);
str = str.replaceAll(“\”",”"”);
str = str.replaceAll(“\’”,”'”);
str = str.replaceAll(“\’”,”&”);

As you can see the code is very simple and clean. Does the job of HTML escaping the given string. But is it efficient?

Version 2:

We shall try to do HTML escaping without using the String.replaceAll() method. The following code analyzes each character in the given string and replaces it with the appropriate escaped value.

StringBuilder strBuilder = new StringBuilder();
int size = strIn.length();
for(int i = 0 ; i < charval =" strIn.charAt(i);">’:
{
strBuilder.append(“>”);
break;
}
case ‘\”:
{
strBuilder.append(“'”);
break;
}
case ‘\”‘:
{
strBuilder.append(“"”);
break;
}
case ‘&’:
{
strBuilder.append(“&”);
break;
}
default:
{
strBuilder.append(charVal);
}
}
}

String escapedString = strBuilder.toString();

Results:

Each version of the code was run 1000 times in a loop and here are the results

Version 1: Time taken for String.replaceAll(str,str) ::250 ms
Version 2: Time taken for custom replace all code ::15 ms

On running both the version of the code, it is found the version 2 which did not use the String.replaceAll() was on an average 10 to 15x faster than the version 1 of the code which used String.replaceAll().

Performance difference in String And StringBuilder

One of the most common mistake we do with Strings is when we try to concatenate multiple strings to form a bigger string. There are a lot of cases where we try to build a large string like, building a large json string to be passed, building a html, building a bulk insert sql, etc., In majority of cases we would be looping to create the large string.

In this experiment we shall try to create a large string which will contain “hello world” 20000 times.

Version 1:

String largeString = “”;
for(int i = 0 ; i < 20000; i++)
{
largeString = largeString + “hello world”;
}

The code might look alright, let us see how it performs

It took almost 186 Seconds to complete the operation in my PC (P4 3.04GHz, 1GB RAM)

For such a small operation it took more than 3 minutes to complete, surprising?

Let us experiment with another implementation using StringBuilder

Version 2:

StringBuilder largeStringBuilder = new StringBuilder();
for(int i = 0 ; i < 20000 ; i++)
{
largeStringBuilder.append(“hello world”);
}

This code took 15 ms to build the same string. Please notice it is not 15 seconds it is 15 milli seconds. That is almost 12400X faster than the string concatenation done in version 1 of the code.

Source: Codeexperiments

Thursday, November 18, 2010

Listing Hardcoded Strings in a Java Class

The below program Lists all the hard coded strings available in a java source. It will be useful for you to move all the hard coded strings of a java class to a constants file by customizing this program. It is an initial draft of the program.. keep on following this blog for the final version.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Test {

public static void main(String[] args) throws Exception {

String fileName = "D:/workspace/demo/src/util/Utility.java";
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
BufferedReader bis = new BufferedReader(new InputStreamReader(fis));
String strLine;
while((strLine = bis.readLine()) != null) {

while(strLine.contains("\"")) {
int beginIndex = strLine.indexOf('"');
String remString = strLine.substring(beginIndex+1);
int endIndex = remString.indexOf('"');
"+(beginIndex+endIndex));
String temp = strLine.substring(beginIndex, (beginIndex+endIndex+2));
System.out.println("token : "+temp);
strLine = strLine.substring(beginIndex+endIndex+2);

}
}

}

}