From 9dd9fc3a8a75bd2360f16877ab9e5fe5f9c75d5b Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Wed, 7 Jun 2023 11:22:01 +0200 Subject: [PATCH] classlib: improve performance of several String methods --- .../org/teavm/classlib/java/lang/TString.java | 64 ++++++++++++------- 1 file changed, 41 insertions(+), 23 deletions(-) diff --git a/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java b/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java index 16c7d6dd3..baf3f02d0 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java +++ b/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java @@ -15,7 +15,6 @@ */ package org.teavm.classlib.java.lang; -import java.util.Iterator; import java.util.Locale; import org.teavm.backend.javascript.spi.GeneratedBy; import org.teavm.classlib.java.io.TSerializable; @@ -33,12 +32,14 @@ import org.teavm.dependency.PluggableDependency; import org.teavm.interop.NoSideEffects; public class TString extends TObject implements TSerializable, TComparable, TCharSequence { + private static final char[] EMPTY_CHARS = new char[0]; + private static final TString EMPTY = new TString(); public static final TComparator CASE_INSENSITIVE_ORDER = (o1, o2) -> o1.compareToIgnoreCase(o2); private char[] characters; private transient int hashCode; public TString() { - this.characters = new char[0]; + this.characters = EMPTY_CHARS; } public TString(TString other) { @@ -59,6 +60,12 @@ public class TString extends TObject implements TSerializable, TComparable endIndex) { throw new TIndexOutOfBoundsException(); } + if (beginIndex == endIndex) { + return EMPTY; + } + if (beginIndex == 0 && endIndex == length()) { + return this; + } return new TString(characters, beginIndex, endIndex - beginIndex); } @@ -408,7 +420,11 @@ public class TString extends TObject implements TSerializable, TComparable elements) { - Iterator iter = elements.iterator(); + var iter = elements.iterator(); if (!iter.hasNext()) { return ""; } - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.append(iter.next()); while (iter.hasNext()) { sb.append(delimiter); @@ -750,20 +766,22 @@ public class TString extends TObject implements TSerializable, TComparable