HHH-14190 Improve efficiency of StringHelper#isBlank

This commit is contained in:
Sanne Grinovero 2020-08-26 12:43:30 +01:00
parent 9c6805fdd3
commit 03a1bb5ac8
2 changed files with 27 additions and 1 deletions

View File

@ -473,7 +473,20 @@ public final class StringHelper {
}
public static boolean isBlank(String string) {
return isEmpty( string ) || isEmpty( string.trim() );
//TODO use Java 11's more efficient String#isBlank - currently we still require Java 8 compatibility
if ( string == null || string.isEmpty() ) {
return true;
}
else {
//Else: we need to check all characters, preferably without using String#trim() so to
//not allocate temporary strings
for ( int i = 0; i < string.length(); i++ ) {
if ( ! Character.isWhitespace( string.charAt( i ) ) ) {
return false;
}
}
return true;
}
}
/**

View File

@ -18,6 +18,7 @@ import org.hibernate.internal.util.StringHelper;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@ -44,6 +45,18 @@ public class StringHelperTest extends BaseUnitTestCase {
assertEquals( "internal.util.StringHelper", StringHelper.partiallyUnqualify( STRING_HELPER_FQN, BASE_PACKAGE ) );
}
@Test
public void testIsBlank() {
assertFalse( StringHelper.isBlank( "A" ) );
assertFalse( StringHelper.isBlank( " a" ) );
assertFalse( StringHelper.isBlank( "a " ) );
assertFalse( StringHelper.isBlank( "a\t" ) );
assertTrue( StringHelper.isBlank( "\t\n" ) );
assertTrue( StringHelper.isBlank( null ) );
assertTrue( StringHelper.isBlank( "" ) );
assertTrue( StringHelper.isBlank( " " ) );
}
@Test
public void testBasePackageCollapsing() {
assertNull( StringHelper.collapseQualifierBase( null, BASE_PACKAGE ) );