Optimization code (#10158)

* Use StringBuilder#append(Char) to improve performance

* replace with lambda

* The original implementation calls the get method twice.Replace it with computeIfAbsent.

Co-authored-by: huangdeyuan <295258290@qq.com>
This commit is contained in:
hdyztmdqd 2022-06-27 11:16:15 +08:00 committed by GitHub
parent d2d1b99b15
commit 06cb5cdd3f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 68 additions and 83 deletions

View File

@ -116,10 +116,10 @@ public class RouterSnapshotNode<T> {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[ ")
.append(name)
.append(" ")
.append(' ')
.append("(Input: ").append(beforeSize).append(") ")
.append("(Current Node Output: ").append(nodeOutputSize).append(") ")
.append("(Chain Node Output: ").append(chainOutputSize).append(")")
.append("(Chain Node Output: ").append(chainOutputSize).append(')')
.append(routerMessage == null ? "" : " Router message: ")
.append(routerMessage == null ? "" : routerMessage)
.append(" ] ");

View File

@ -103,7 +103,7 @@ public abstract class MeshRuleRouter<T> extends AbstractStateRouter<T> implement
BitList<Invoker<T>> destination = meshRuleCache.getSubsetInvokers(appName, subset);
result = result.or(destination);
if (stringBuilder != null) {
stringBuilder.append("Match App: ").append(appName).append(" Subset: ").append(subset).append(" ");
stringBuilder.append("Match App: ").append(appName).append(" Subset: ").append(subset).append(' ');
}
}
}

View File

@ -49,7 +49,7 @@ public class RouterGroupingState<T> {
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(routerName)
.append(" ")
.append(' ')
.append(" Total: ")
.append(total)
.append("\n");

View File

@ -378,11 +378,11 @@ class URL implements Serializable {
if (StringUtils.isNotEmpty(getHost())) {
if (StringUtils.isNotEmpty(getUsername()) || StringUtils.isNotEmpty(getPassword())) {
ret.append("@");
ret.append('@');
}
ret.append(getHost());
if (getPort() != 0) {
ret.append(":");
ret.append(':');
ret.append(getPort());
}
}
@ -406,7 +406,7 @@ class URL implements Serializable {
ret.append(getUsername());
}
ret.append(":");
ret.append(':');
if (StringUtils.isNotEmpty(getPassword())) {
ret.append(getPassword());

View File

@ -108,7 +108,7 @@ public abstract class Mixin {
code.append('d').append(i).append(" = (").append(dcs[i].getName()).append(")$1[").append(i).append("];\n");
if (MixinAware.class.isAssignableFrom(dcs[i])) {
code.append("d").append(i).append(".setMixinInstance(this);\n");
code.append('d').append(i).append(".setMixinInstance(this);\n");
}
}
ccp.addConstructor(Modifier.PUBLIC, new Class<?>[]{Object[].class}, code.toString());

View File

@ -150,7 +150,7 @@ public class Proxy {
StringBuilder code = new StringBuilder("Object[] args = new Object[").append(pts.length).append("];");
for (int j = 0; j < pts.length; j++) {
code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(";");
code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(';');
}
code.append(" Object ret = handler.invoke(this, methods[").append(ix).append("], args);");
if (!Void.TYPE.equals(rt)) {

View File

@ -1095,28 +1095,27 @@ public class ExtensionLoader<T> {
}
}
if (urlListMap.get(resourceURL) != null) {
return urlListMap.get(resourceURL);
}
List<String> contentList = urlListMap.computeIfAbsent(resourceURL,key->{
List<String> newContentList = new ArrayList<>();
List<String> newContentList = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
final int ci = line.indexOf('#');
if (ci >= 0) {
line = line.substring(0, ci);
}
line = line.trim();
if (line.length() > 0) {
newContentList.add(line);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
final int ci = line.indexOf('#');
if (ci >= 0) {
line = line.substring(0, ci);
}
line = line.trim();
if (line.length() > 0) {
newContentList.add(line);
}
}
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
urlListMap.put(resourceURL, newContentList);
return newContentList;
return newContentList;
});
return contentList;
}
private boolean isIncluded(String className, String... includedPackages) {

View File

@ -79,9 +79,9 @@ public class Profiler {
long offset = entry.getStartTime() - startTime;
List<String> lines = new LinkedList<>();
stringBuilder.append("+-[ Offset: ")
.append(offset / 1000_000).append(".").append(String.format("%06d", offset % 1000_000))
.append(offset / 1000_000).append('.').append(String.format("%06d", offset % 1000_000))
.append("ms; Usage: ")
.append(usage / 1000_000).append(".").append(String.format("%06d", usage % 1000_000))
.append(usage / 1000_000).append('.').append(String.format("%06d", usage % 1000_000))
.append("ms, ")
.append(percent)
.append("% ] ")

View File

@ -99,21 +99,18 @@ public class ExecutorUtil {
private static void newThreadToCloseExecutor(final ExecutorService es) {
if (!isTerminated(es)) {
SHUTDOWN_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
es.shutdownNow();
if (es.awaitTermination(10, TimeUnit.MILLISECONDS)) {
break;
}
SHUTDOWN_EXECUTOR.execute(() -> {
try {
for (int i = 0; i < 1000; i++) {
es.shutdownNow();
if (es.awaitTermination(10, TimeUnit.MILLISECONDS)) {
break;
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
});
}

View File

@ -45,7 +45,7 @@ public class UnsafeStringWriterTest {
@Test
public void testAppend() {
UnsafeStringWriter writer = new UnsafeStringWriter();
writer.append("a");
writer.append('a');
writer.append("abc", 1, 2);
writer.append('c');
writer.flush();

View File

@ -453,22 +453,19 @@ public abstract class AbstractMetadataReport implements MetadataReport {
if (retryScheduledFuture == null) {
synchronized (retryCounter) {
if (retryScheduledFuture == null) {
retryScheduledFuture = retryExecutor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
// Check and connect to the metadata
try {
int times = retryCounter.incrementAndGet();
logger.info("start to retry task for metadata report. retry times:" + times);
if (retry() && times > retryTimesIfNonFail) {
cancelRetryTask();
}
if (times > retryLimit) {
cancelRetryTask();
}
} catch (Throwable t) { // Defensive fault tolerance
logger.error("Unexpected error occur at failed retry, cause: " + t.getMessage(), t);
retryScheduledFuture = retryExecutor.scheduleWithFixedDelay(() -> {
// Check and connect to the metadata
try {
int times = retryCounter.incrementAndGet();
logger.info("start to retry task for metadata report. retry times:" + times);
if (retry() && times > retryTimesIfNonFail) {
cancelRetryTask();
}
if (times > retryLimit) {
cancelRetryTask();
}
} catch (Throwable t) { // Defensive fault tolerance
logger.error("Unexpected error occur at failed retry, cause: " + t.getMessage(), t);
}
}, 500, retryPeriod, TimeUnit.MILLISECONDS);
}

View File

@ -82,7 +82,7 @@ public abstract class AbstractServiceAnnotationProcessor extends AbstractProcess
});
methodSignatureBuilder.append(method.getReturnType())
.append(" ")
.append(' ')
.append(method.toString());
return methodSignatureBuilder.toString();

View File

@ -51,7 +51,7 @@ public class ChangeTelnet implements BaseCommand {
StringBuilder buf = new StringBuilder();
if ("/".equals(message) || "..".equals(message)) {
String service = channel.attr(SERVICE_KEY).getAndRemove();
buf.append("Cancelled default service ").append(service).append(".");
buf.append("Cancelled default service ").append(service).append('.');
} else {
boolean found = false;
for (Exporter<?> exporter : dubboProtocol.getExporters()) {

View File

@ -57,7 +57,7 @@ public class GetRouterSnapshot implements BaseCommand {
for (Map.Entry<Registry, MigrationInvoker<?>> invokerEntry : invokerMap.entrySet()) {
Directory<?> directory = invokerEntry.getValue().getDirectory();
StateRouter<?> headStateRouter = directory.getRouterChain().getHeadStateRouter();
stringBuilder.append(metadata.getServiceKey()).append("@").append(Integer.toHexString(System.identityHashCode(metadata)))
stringBuilder.append(metadata.getServiceKey()).append('@').append(Integer.toHexString(System.identityHashCode(metadata)))
.append("\n")
.append("[ All Invokers:").append(directory.getAllInvokers().size()).append(" ] ")
.append("[ Valid Invokers: ").append(((AbstractDirectory<?>)directory).getValidInvokers().size()).append(" ]\n")

View File

@ -133,7 +133,7 @@ public class InvokeTelnet implements BaseCommand {
if (!StringUtils.isEmpty(service)) {
buf.append("Use default service ").append(service).append(".");
buf.append("Use default service ").append(service).append('.');
}
if (selectedProvider == null) {
buf.append("\r\nNo such service ").append(service);

View File

@ -57,16 +57,11 @@ public class QosProcessHandler extends ByteToMessageDecoder {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
welcomeFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (welcome != null) {
ctx.write(Unpooled.wrappedBuffer(welcome.getBytes()));
ctx.writeAndFlush(Unpooled.wrappedBuffer(PROMPT.getBytes()));
}
welcomeFuture = ctx.executor().schedule(() -> {
if (welcome != null) {
ctx.write(Unpooled.wrappedBuffer(welcome.getBytes()));
ctx.writeAndFlush(Unpooled.wrappedBuffer(PROMPT.getBytes()));
}
}, 500, TimeUnit.MILLISECONDS);
}

View File

@ -328,7 +328,7 @@ public class ServiceInstancesChangedListener {
}
builder.append(entry.getKey());
builder.append(" ");
builder.append(' ');
}
if (emptyMetadataNum > 0) {

View File

@ -134,14 +134,11 @@ public class MulticastRegistry extends FailbackRegistry {
}
this.cleanPeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_SESSION_TIMEOUT);
if (url.getParameter("clean", true)) {
this.cleanFuture = cleanExecutor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
clean(); // Remove the expired
} catch (Throwable t) { // Defensive fault tolerance
logger.error("Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), t);
}
this.cleanFuture = cleanExecutor.scheduleWithFixedDelay(() -> {
try {
clean(); // Remove the expired
} catch (Throwable t) { // Defensive fault tolerance
logger.error("Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), t);
}
}, cleanPeriod, cleanPeriod, TimeUnit.MILLISECONDS);
} else {

View File

@ -143,7 +143,7 @@ public class JettyLoggerAdapter extends AbstractLogger {
int bracesIndex = msg.indexOf(braces, start);
if (bracesIndex < 0) {
builder.append(msg.substring(start));
builder.append(" ");
builder.append(' ');
builder.append(arg);
start = msg.length();
} else {

View File

@ -297,7 +297,7 @@ public class DubboTestChecker implements TestExecutionListener {
public static String getFullStacktrace(Thread thread, StackTraceElement[] stackTrace) {
StringBuilder sb = new StringBuilder("Thread: \"" + thread.getName() + "\"" + " Id="
+ thread.getId());
sb.append(" ").append(thread.getState());
sb.append(' ').append(thread.getState());
sb.append('\n');
if (stackTrace == null) {
stackTrace = thread.getStackTrace();