1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-11-25 21:42:07 +01:00

[core] Cache length in LazyStringBuilder

This commit is contained in:
Florian Schmaus 2023-11-26 21:24:17 +01:00
parent 9203907e66
commit 70e48300a6

View file

@ -1,6 +1,6 @@
/** /**
* *
* Copyright 2014-2019 Florian Schmaus * Copyright 2014-2023 Florian Schmaus
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -25,9 +25,11 @@ public class LazyStringBuilder implements Appendable, CharSequence {
private final List<CharSequence> list; private final List<CharSequence> list;
private String cache; private String cache;
private int cachedLength = -1;
private void invalidateCache() { private void invalidateCache() {
cache = null; cache = null;
cachedLength = -1;
} }
public LazyStringBuilder() { public LazyStringBuilder() {
@ -65,9 +67,10 @@ public class LazyStringBuilder implements Appendable, CharSequence {
@Override @Override
public int length() { public int length() {
if (cache != null) { if (cachedLength >= 0) {
return cache.length(); return cachedLength;
} }
int length = 0; int length = 0;
try { try {
for (CharSequence csq : list) { for (CharSequence csq : list) {
@ -78,6 +81,8 @@ public class LazyStringBuilder implements Appendable, CharSequence {
StringBuilder sb = safeToStringBuilder(); StringBuilder sb = safeToStringBuilder();
throw new RuntimeException("The following LazyStringBuilder threw a NullPointerException: " + sb, npe); throw new RuntimeException("The following LazyStringBuilder threw a NullPointerException: " + sb, npe);
} }
cachedLength = length;
return length; return length;
} }