상세 컨텐츠

본문 제목

자바 최적화를 위한 5가지

개발

by 동동주1123 2012. 1. 27. 17:49

본문

1. 불필요한 캐스팅 피한다.

class MyCastingClass { public Object myMethod() { String myString = "Some data"; Object myObj = (Object) myString; return myObj; } }


class MyCastingClass {
	public Object myMethod() {
		return "Some data";
	}
}

 

2. 일반적인 하위 표현식 제거

int someNumber = (someValue * number1 / number2) + otherValue; int someNumber2 = (someValue * number1 / number2) +

final int constantCalculation = (someValue * number1 / number2);
int someNumber = (constantCalculation) + otherValue;
int someNumber2 = (constantCalculation) + otherValue2;
 



3. Use StringBuffer (or StringBuilder) instead of string for non-constant strings

class MyStringClass { public void myMethod() { String myString = "Some data"; for (int i = 0; i < 20; i++) { myString += getMoreChars(); } } }



class MyCastingClass {
	public Object myMethod() {
		String myString = "Some data";
		StringBuffer myBuffer = new StringBuffer();

		for (int i = 0; i < 20; i++) {
			myBuffer.append(getMoreChars());
		}
		myString = myBuffer.toString();
	}
}

 

4. Use Short Circuit Boolean Operators

class MyShortCircuitClass { public void myMethod() { if (someValue.equals("true") | someValue.equals("false")) { System.out.println("valid boolean"); } } }


class MyCastingClass {
	public void myMethod() {
		if ("true".equals(someValue) || "false".equals(someValue)) {
			System.out.println("valid boolean");
		}
	}
}

Here’s a table describing four of Java’s boolean operators:



5.  Use length() instead of equals() to find the length of a string

 class MyStringClass {

	public boolean myTestMethod() {
		return myString.equals("");
	}
}


class MyCastingClass {
	public void myMethod() {
		public boolean myTestMethod() {
			// which really does myString.length() == 0 behind the schenes
			return myString.isEmpty();
		}
	}
}

 

'개발' 카테고리의 다른 글

아파치 + 톰켓 연동  (0) 2012.02.02
우분투에 VSFTP 설치하기  (0) 2012.01.14
AXIS2 예제 사이트  (0) 2011.11.10

관련글 더보기