Java Char Lookup Table

Use a char lookup table to instantly convert characters with array element accesses.
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.

Java program that uses char lookup table 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); } } } Output 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.ROT13Caesar Cipher
Some limitations, summary. Char lookup tables must accommodate all characters, or use a range check for values. This ensures no exceptions are thrown.Exceptions
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls