2
\$\begingroup\$

In a game that I am making, I have a look in my game which goes through an array, and lists the things in the array

public void listOpen() {
    ArrayList<String> open = main.getOpenable();
    for(int i = 0; i < open.size(); i++) {
        String value = open.get(i);
        textWindow.append(value + "\n");
        error.setScroll();
    }
}

Sometimes when I'm running the program I notice that it lags slightly. Is there anyway I can make it more efficient?

\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

Make only one textWindow.append() operation and consider using StringBuilder, to construct string to append.

public void listOpen() {
    ArrayList<String> open = main.getOpenable();
    StringBuilder appendBuilder = new StringBuilder();
    for(int i = 0; i < open.size(); i++) {
        String value = open.get(i);
        appendBuilder.append(value).append("\n");
        error.setScroll();
    }
    textWindow.append(appendBuilder.toString());
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can also pull out the setScroll call, if it's a UI call then only the last call will have an effect. \$\endgroup\$ Oct 6, 2016 at 10:56
2
\$\begingroup\$

I just want to add a couple of points.

Code to the Interface instead of its Implementation:

When declaring an object you want to declare it as the highest level object needed as opposed to its specific implementation.

In this case you wrote:

ArrayList<String> open = main.getOpenable();

This requires that main.getOpenable() returns an ArrayList. What happens if in the future you decide to have it return a LinkedList? It could break the current code.

It is a much better idea to simply do:

List<String> open = main.getOpenable();

Now you can pass it any sort of List with no issues.

Note: Obviously you need to ensure that the interface contains all the methods you need to call, but here that is the case.

You can use a for-each loop to iterate over the List:

This may be a style choice, but it leads to cleaner code. Consider the following (using the StringBuilder effeciency):

public void listOpen() {
    ArrayList<String> open = main.getOpenable();
    StringBuilder appendBuilder = new StringBuilder();
    for(String value : open) {
        appendBuilder.append(value).append("\n");
        error.setScroll();
    }
    textWindow.append(appendBuilder.toString());
}

Here the benefit is small, but it does remove a line of code and removes some of the possibility of errors.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.