Skip to content

Commit

Permalink
Address some perf issues reported by PMD 2.2:
Browse files Browse the repository at this point in the history
Redundant Field Initializer 52
Avoid Instantiating Objects In Loops 15
Consecutive Appends Should Reuse 14
Inefficient String Buffering 8
Use String Buffer For String Appends 7
Optimizable To Array Call 6
Append Character With Char 5
Insufficient String Buffer Declaration 3
Inefficient Empty String Check 3
Add Empty String 2
Avoid File Stream 1
Use Index Of Char 1
Simplify Starts With 1
  • Loading branch information
fniephaus committed Jun 15, 2020
1 parent 948eb21 commit 6186969
Show file tree
Hide file tree
Showing 31 changed files with 152 additions and 241 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@
import de.hpi.swa.trufflesqueak.shared.SqueakLanguageOptions;

public final class TruffleSqueakLauncher extends AbstractLanguageLauncher {
private boolean headless = false;
private boolean printImagePath = false;
private boolean quiet = false;
private boolean headless;
private boolean printImagePath;
private boolean quiet;
private String[] imageArguments = new String[0];
private String imagePath = null;
private String sourceCode = null;
private boolean enableTranscriptForwarding = false;
private String logHandlerMode = null;
private String imagePath;
private String sourceCode;
private boolean enableTranscriptForwarding;
private String logHandlerMode;

public static void main(final String[] arguments) throws RuntimeException {
new TruffleSqueakLauncher().launch(arguments);
Expand All @@ -51,7 +51,7 @@ protected List<String> preprocessArguments(final List<String> arguments, final M
if (isExistingImageFile(arg)) {
imagePath = Paths.get(arg).toAbsolutePath().toString();
final List<String> remainingArguments = arguments.subList(i + 1, arguments.size());
imageArguments = remainingArguments.toArray(new String[remainingArguments.size()]);
imageArguments = remainingArguments.toArray(new String[0]);
break;
} else if (SqueakLanguageOptions.CODE_FLAG.equals(arg) || SqueakLanguageOptions.CODE_FLAG_SHORT.equals(arg)) {
sourceCode = arguments.get(++i);
Expand Down Expand Up @@ -128,7 +128,7 @@ protected int execute(final Context.Builder contextBuilder) {
} catch (final IllegalArgumentException e) {
if (e.getMessage().contains("Could not find option with name " + SqueakLanguageConfig.ID)) {
final String thisPackageName = getClass().getPackage().getName();
final String parentPackageName = thisPackageName.substring(0, thisPackageName.lastIndexOf("."));
final String parentPackageName = thisPackageName.substring(0, thisPackageName.lastIndexOf('.'));
throw abort(String.format("Failed to load TruffleSqueak. Please ensure '%s' is on the Java class path.", parentPackageName));
} else {
throw e;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public final class LogHandlerAccessor {
private static boolean firstTime = true;

public static Handler createLogHandler(final String mode) {
PrintStream output = null;
switch (mode) {
case "mapped":
if (firstTime) {
Expand All @@ -59,16 +58,14 @@ public static Handler createLogHandler(final String mode) {
firstTime = false;
println("TruffleSqueak log handler logging to standard err");
}
output = System.err;
break;
return new StandardPrintStreamHandler(System.err);
default:
if (firstTime) {
firstTime = false;
println("TruffleSqueak log handler logging to standard out");
}
output = System.out;
return new StandardPrintStreamHandler(System.out);
}
return new StandardPrintStreamHandler(output);
}

protected static Path getLogPath() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

import java.io.File;
import java.io.FileFilter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
Expand Down Expand Up @@ -126,13 +128,13 @@ private static String getPathToTestImage() {
}

private static String getPathToTestImage(final String imageName) {
File currentDirectory = new File(System.getProperty("user.dir"));
Path currentDirectory = Paths.get(System.getProperty("user.dir")).toAbsolutePath();
while (currentDirectory != null) {
final String pathToImage = currentDirectory.getAbsolutePath() + File.separator + "images" + File.separator + imageName;
if (new File(pathToImage).exists()) {
return pathToImage;
final File file = currentDirectory.resolve("images").resolve(imageName).toFile();
if (file.exists()) {
return file.getAbsolutePath();
}
currentDirectory = currentDirectory.getParentFile();
currentDirectory = currentDirectory.getParent();
}
return null;
}
Expand Down Expand Up @@ -274,17 +276,17 @@ private static String[] truffleSqueakTestCaseNames() {
testCaseNames.add(classDirectories.getName().substring(0, classDirectories.getName().lastIndexOf(".class")));
}
}
return testCaseNames.toArray(new String[testCaseNames.size()]);
return testCaseNames.toArray(new String[0]);
}

protected static final String getPathToInImageCode() {
File currentDirectory = new File(System.getProperty("user.dir"));
Path currentDirectory = Paths.get(System.getProperty("user.dir")).toAbsolutePath();
while (currentDirectory != null) {
final String pathToImage = currentDirectory.getAbsolutePath() + File.separator + "src" + File.separator + "image" + File.separator + "src";
if (new File(pathToImage).isDirectory()) {
return pathToImage;
final File file = currentDirectory.resolve("src").resolve("image").resolve("src").toFile();
if (file.isDirectory()) {
return file.getAbsolutePath();
}
currentDirectory = currentDirectory.getParentFile();
currentDirectory = currentDirectory.getParent();
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

import de.hpi.swa.trufflesqueak.test.SqueakTests.SqueakTest;
import de.hpi.swa.trufflesqueak.test.SqueakTests.TestType;
import de.hpi.swa.trufflesqueak.util.MiscUtils;

/**
* Run tests from the Squeak image.
Expand Down Expand Up @@ -66,7 +67,7 @@ public class SqueakSUnitTest extends AbstractSqueakTestCaseWithImage {

@Parameter public SqueakTest test;

private static boolean truffleSqueakPackagesLoaded = false;
private static boolean truffleSqueakPackagesLoaded;
private static boolean stopRunningSuite;

@Parameters(name = "{0} (#{index})")
Expand All @@ -76,7 +77,7 @@ public static Collection<SqueakTest> getParameters() {

private static Stream<SqueakTest> selectTestsToRun() {
final String toRun = System.getProperty(TEST_CLASS_PROPERTY);
if (toRun != null && !toRun.trim().isEmpty()) {
if (toRun != null && !MiscUtils.isBlank(toRun)) {
return SqueakTests.getTestsToRun(toRun);
}
return SqueakTests.allTests();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,17 @@ final class Target_de_hpi_swa_trufflesqueak_io_SqueakDisplay implements SqueakDi
private Cursor cursor = WordFactory.nullPointer();
private NativeObject bitmap;
@CompilationFinal private int inputSemaphoreIndex;
private boolean deferUpdates = false;
private boolean textureDirty = false;
private boolean deferUpdates;
private boolean textureDirty;
private int width;
private int height;
private int bpp = 4; // TODO: for 32bit only!

private int lastMouseXPos;
private int lastMouseYPos;
private int button = 0;
private int key = 0;
private boolean isKeyDown = false;
private int button;
private int key;
private boolean isKeyDown;

Target_de_hpi_swa_trufflesqueak_io_SqueakDisplay(final SqueakImageContext image) {
this.image = image;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ public final class SqueakImageContext {
public final NativeObject runWithInSelector = new NativeObject(this);
public final ArrayObject primitiveErrorTable = new ArrayObject(this);
public final ArrayObject specialSelectors = new ArrayObject(this);
@CompilationFinal private ClassObject smallFloatClass = null;
@CompilationFinal private ClassObject byteSymbolClass = null;
@CompilationFinal private ClassObject foreignObjectClass = null;
@CompilationFinal private ClassObject smallFloatClass;
@CompilationFinal private ClassObject byteSymbolClass;
@CompilationFinal private ClassObject foreignObjectClass;

public final ArrayObject specialObjectsArray = new ArrayObject(this);
public final ClassObject metaClass = new ClassObject(this);
Expand Down Expand Up @@ -134,14 +134,14 @@ public final class SqueakImageContext {
@CompilationFinal private SqueakImage squeakImage;

/* Stack Management */
public int stackDepth = 0;
public int stackDepth;
public ContextObject lastSeenContext;

@CompilationFinal private ClassObject compilerClass = null;
@CompilationFinal private ClassObject parserClass = null;
private PointersObject parserSharedInstance = null;
@CompilationFinal private PointersObject scheduler = null;
@CompilationFinal private ClassObject wideStringClass = null;
@CompilationFinal private ClassObject compilerClass;
@CompilationFinal private ClassObject parserClass;
private PointersObject parserSharedInstance;
@CompilationFinal private PointersObject scheduler;
@CompilationFinal private ClassObject wideStringClass;

/* Plugins */
public final B2D b2d = new B2D(this);
Expand All @@ -152,9 +152,9 @@ public final class SqueakImageContext {

/* Error detection for headless execution */
@CompilationFinal(dimensions = 1) public static final byte[] DEBUG_ERROR_SELECTOR_NAME = "debugError:".getBytes();
@CompilationFinal private NativeObject debugErrorSelector = null;
@CompilationFinal private NativeObject debugErrorSelector;
@CompilationFinal(dimensions = 1) public static final byte[] DEBUG_SYNTAX_ERROR_SELECTOR_NAME = "debugSyntaxError:".getBytes();
@CompilationFinal private NativeObject debugSyntaxErrorSelector = null;
@CompilationFinal private NativeObject debugSyntaxErrorSelector;

public SqueakImageContext(final SqueakLanguage squeakLanguage, final SqueakLanguage.Env environment) {
language = squeakLanguage;
Expand Down Expand Up @@ -517,9 +517,9 @@ public void setImagePath(final String path) {
public String getImageDirectory() {
final Path parent = Paths.get(getImagePath()).getParent();
if (parent != null) {
return "" + parent.getFileName(); // Avoids NullPointerExceptions.
return parent.toString();
} else {
throw SqueakException.create("`parent` should not be `null`.");
throw SqueakException.create("Could not determine image directory.");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

public final class SqueakImageFlags {
@CompilationFinal private long oldBaseAddress = -1;
@CompilationFinal private int fullScreenFlag = 0;
@CompilationFinal private int fullScreenFlag;
@CompilationFinal private int imageFloatsBigEndian;
@CompilationFinal private boolean flagInterpretedMethods;
@CompilationFinal private boolean preemptionYields;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ public final class SqueakImageReader {
private int headerFlags;
private short maxExternalSemaphoreTableSize;
private long firstSegmentSize;
private int position = 0;
private int position;
private long currentAddressSwizzle;
private final byte[] emptyBytes = new byte[0];

private SqueakImageChunk freePageList = null;
private SqueakImageChunk freePageList;

private SqueakImageReader(final SqueakImageContext image) {
final TruffleFile truffleFile = image.env.getPublicTruffleFile(image.getImagePath());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public Object getMembers(@SuppressWarnings("unused") final boolean includeIntern
members.add(WRAPPED_MEMBER);
members.addAll(getFields().keySet());
members.addAll(getMethods().keySet());
cachedMembers = new InteropArray(members.toArray(new String[members.size()]));
cachedMembers = new InteropArray(members.toArray(new String[0]));
}
return cachedMembers;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
Expand Down Expand Up @@ -74,11 +73,10 @@ public final class SqueakDisplay implements SqueakDisplayInterface {

@CompilationFinal private int inputSemaphoreIndex = -1;

public int buttons = 0;
private Dimension rememberedWindowSize = null;
private Point rememberedWindowLocation = null;
private boolean deferUpdates = false;
private int[] cursorMergedWords = new int[SqueakIOConstants.CURSOR_HEIGHT];
public int buttons;
private Dimension rememberedWindowSize;
private Point rememberedWindowLocation;
private boolean deferUpdates;

public SqueakDisplay(final SqueakImageContext image) {
this.image = image;
Expand Down Expand Up @@ -313,16 +311,13 @@ public void setCursor(final int[] cursorWords, final int[] mask, final int width
canvas.setCursor(cursor);
}

private int[] mergeCursorWithMask(final int[] cursorWords, final int[] maskWords) {
int cursorWord;
int maskWord;
int bit;
int merged;
private static int[] mergeCursorWithMask(final int[] cursorWords, final int[] maskWords) {
final int[] cursorMergedWords = new int[SqueakIOConstants.CURSOR_HEIGHT];
for (int y = 0; y < SqueakIOConstants.CURSOR_HEIGHT; y++) {
cursorWord = cursorWords[y];
maskWord = maskWords[y];
bit = 0x80000000;
merged = 0;
final int cursorWord = cursorWords[y];
final int maskWord = maskWords[y];
int bit = 0x80000000;
int merged = 0;
for (int x = 0; x < SqueakIOConstants.CURSOR_WIDTH; x++) {
merged = merged | (maskWord & bit) >> x | (cursorWord & bit) >> x + 1;
bit = bit >>> 1;
Expand Down Expand Up @@ -433,14 +428,8 @@ public void drop(final DropTargetDropEvent dtde) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
try {
@SuppressWarnings("unchecked")
final List<File> l = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
final Iterator<File> iter = l.iterator();
final String[] fileList = new String[l.size()];
int i = 0;
while (iter.hasNext()) {
fileList[i++] = iter.next().getCanonicalPath();
}
image.dropPluginFileList = fileList;
final List<File> fileList = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
image.dropPluginFileList = fileList.toArray(new String[0]);
addDragEvent(DRAG.DROP, dtde.getLocation());
dtde.getDropTargetContext().dropComplete(true);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public final class ClassObject extends AbstractSqueakObjectWithClassAndHash {
private final CyclicAssumption methodDictStable = new CyclicAssumption("Method dictionary stability");
private final CyclicAssumption classFormatStable = new CyclicAssumption("Class format stability");

@CompilationFinal private boolean instancesAreClasses = false;
@CompilationFinal private boolean instancesAreClasses;

private ClassObject superclass;
@CompilationFinal private VariablePointersObject methodDict;
Expand Down Expand Up @@ -445,7 +445,7 @@ public Object[] listInteropMembers() {
}
lookupClass = lookupClass.getSuperclassOrNull();
}
return methodNames.toArray(new String[methodNames.size()]);
return methodNames.toArray(new String[0]);
}

public int getBasicInstanceSize() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public enum SLOT_IDENTIFIER {
@CompilationFinal protected int numArgs;
@CompilationFinal protected int numLiterals;
@CompilationFinal protected boolean hasPrimitive;
@CompilationFinal protected boolean needsLargeFrame = false;
@CompilationFinal protected boolean needsLargeFrame;
@CompilationFinal protected int numTemps;

@CompilationFinal(dimensions = 1) private CompiledBlockObject[] innerBlocks;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,10 @@ public String toString() {
return className + ">>" + getNotNilSelector();
}

public String getNotNilSelector() {
private String getNotNilSelector() {
CompilerAsserts.neverPartOfCompilation();
String selector = "DoIt";
final NativeObject selectorObj = getCompiledInSelector();
if (selectorObj != null) {
selector = selectorObj.asStringUnsafe();
} else if (getNumArgs() > 0) {
selector += ":";
for (int i = 1; i < getNumArgs(); i++) {
selector += "with:";
}
}
return selector;
return selectorObj == null ? "DoIt" : selectorObj.asStringUnsafe();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ public final class ContextObject extends AbstractSqueakObjectWithHash {
@CompilationFinal private MaterializedFrame truffleFrame;
@CompilationFinal private PointersObject process;
@CompilationFinal private int size;
private boolean hasModifiedSender = false;
private boolean escaped = false;
private boolean hasModifiedSender;
private boolean escaped;

private ContextObject(final SqueakImageContext image, final long hash) {
super(image, hash);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public void write(final SqueakImageWriter writer) {
@Override
public String toString() {
CompilerAsserts.neverPartOfCompilation();
return "" + doubleValue;
return Double.toString(doubleValue);
}

public FloatObject shallowCopy() {
Expand Down
Loading

0 comments on commit 6186969

Please sign in to comment.