General discussion

Locked

Add custom XSLT functionality

By Mark W. Kaelin Editor ·
The Jan. 8, XML TechMail discusses transformations and how some are not possible with stock XSLT functionality. Will this tip explaining how to add new functions to your stylesheets using the Apache Xalan XSLT engine and custom Java extensions help you with your transformations? Tell us how.

This conversation is currently closed to new comments.

1 total post (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

StringBuffer not String if you append!

by SnoopDoug In reply to Add custom XSLT functiona ...

A couple of comments on your code. You should always use StringBuffer instead of String when you are modifying the String. Also, if you call the same method more than once (ala length), create a temporary variable to hold the value. It's much fasterand less typing.

I benchmarked 1000 iterations of your version of reverse versus mine and the String w/multiple length() invocations took 40 milliseconds, versus 10 with StringBuffer and a local variable. Here's my code:

import java.util.Calendar;

public class test2 {

public static String reverse(String str) {
String retval = "";
char[] b = new char[str.length()];
str.getChars(0, str.length(), b, 0);
for (int i = (b.length - 1); i >= 0; i--) {
retval += b;
}
return retval;
}

static String reverse2(String s) {
StringBuffer sb = new StringBuffer();

int len = s.length();

char[] b = new char[len];
s.getChars(0, len, b, 0);for (int i = len - 1; i >= 0; i--) {
sb.append(b);
}

return sb.toString();
}

public static void main(String [] args) {

String s = "abcdefg";

Calendar start1 = Calendar.getInstance();

for (int i = 0; i < 999; i++) {
String t1 = reverse(s);
} // end of for (int i = 0; i < 999; i++)

Calendar start2 = Calendar.getInstance();

for (int i = 0; i < 999; i++) {
String t1 = reverse2(s);
} // end of for (int i = 0; i < 999; i++)

Calendar end = Calendar.getInstance();

long duration1 = start2.getTimeInMillis() - start1.getTimeInMillis();
long duration2 = end.getTimeInMillis() - start2.getTimeInMillis();

System.out.println("It took " + duration1 + " milliseconds to reverseusing String");
System.out.println("It took " + duration2 + " milliseconds to reverse using StringBuffer");
}
}

Back to Web Development Forum
1 total post (Page 1 of 1)  

Related Discussions

Related Forums