Skip to content

Commit

Permalink
Reuse short Char and Varchar type instances
Browse files Browse the repository at this point in the history
Share ("cache") instances for short `char` and `varchar` types.
- type instantiation can be expensive (see
  96a009e)
- it allows caching things further, like in `getRange()`.
  • Loading branch information
findepi committed Nov 9, 2022
1 parent 4d3de4e commit ccab7db
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions core/trino-spi/src/main/java/io/trino/spi/type/CharType.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ public final class CharType
private static final TypeOperatorDeclaration TYPE_OPERATOR_DECLARATION = extractOperatorDeclaration(CharType.class, lookup(), Slice.class);

public static final int MAX_LENGTH = 65_536;
private static final CharType[] CACHED_INSTANCES = new CharType[128];

static {
for (int i = 0; i < CACHED_INSTANCES.length; i++) {
CACHED_INSTANCES[i] = new CharType(i);
}
}

private final int length;
private volatile Optional<Range> range;
Expand All @@ -67,6 +74,9 @@ public static CharType createCharType(long length)

public static CharType createCharType(int length)
{
if (0 <= length && length < CACHED_INSTANCES.length) {
return CACHED_INSTANCES[length];
}
return new CharType(length);
}

Expand Down
11 changes: 11 additions & 0 deletions core/trino-spi/src/main/java/io/trino/spi/type/VarcharType.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ public final class VarcharType
public static final int MAX_LENGTH = Integer.MAX_VALUE - 1;
public static final VarcharType VARCHAR = new VarcharType(UNBOUNDED_LENGTH);

private static final VarcharType[] CACHED_INSTANCES = new VarcharType[128];

static {
for (int i = 0; i < CACHED_INSTANCES.length; i++) {
CACHED_INSTANCES[i] = new VarcharType(i);
}
}

public static VarcharType createUnboundedVarcharType()
{
return VARCHAR;
Expand All @@ -59,6 +67,9 @@ public static VarcharType createVarcharType(int length)
// Use createUnboundedVarcharType for unbounded VARCHAR.
throw new IllegalArgumentException("Invalid VARCHAR length " + length);
}
if (length < CACHED_INSTANCES.length) {
return CACHED_INSTANCES[length];
}
return new VarcharType(length);
}

Expand Down

0 comments on commit ccab7db

Please sign in to comment.