Char lookup table. Character transformations can be slow. We can have elaborate logic in them. With a lookup table, we can instantly map characters.
For ASCII chars, like ABC, we can use a small lookup table of 128 chars. Then we can use char values (like "A") as the index, and store chars in each slot.
Example code. Let us begin with this simple example. We use a char table of 128 elements to store the result of toUpperCase. We store uppercased versions of all chars.
Then We can transform chars with a simple table lookup. No call to Character.toUpperCase is needed.
public class Program {
static char[] table = new char[128];
public static void main(String[] args) {
// Set up the lookup table.
for (int i = 0; i < 128; i++) {
// Get character for this int.
char c = (char) i;
// Convert to uppercase.
char result = Character.toUpperCase(c);
// Store in lookup table field.
table[c] = result;
}
// Loop over string characters.
String name = "Carrot123";
for (int i = 0; i < name.length(); i++) {
// Get char from lookup table based on string char.
char result = table[name.charAt(i)];
// Write results.
System.out.println(name.charAt(i) + "/" + result);
}
}
}C/C
a/A
r/R
r/R
o/O
t/T
1/1
2/2
3/3
Some performance notes. Character lookup tables are an optimization in many programs. They help the most on slow operations—toUpperCase is too fast to show much benefit from a table.
For a cipher, like ROT13 or a Caesar cipher, a char lookup table can show more improvement. And lookup tables (a form of memoization) are excellent for mathematical computations as well.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.