Java programming best practices
Following are some performance tips in Java. We know many of them still do not use them in regular practice.
Compile-Time Initialization
for (int i =0; i < loop; i++)
{
//Looping 10M rounds
String x = "Hello" + "," +" "+ "World";
}
Better way is....
for (int i =0; i < loop; i++)
{
//Looping 10M rounds
String x = new String("Hello" + "," +" "+ "World");
}
-------------------------------------------------------------------------------------------------------------------
Runtime String Initialization
String name = "Smith";
for (int i =0; i < loop; i++)
{
//Looping 1M rounds
String x = "Hello";
x += ",";
x += " Mr.";
x += name;
}
Better way is....
String name = "Smith";
for (int i =0; i < loop; i++)
{
//Looping 1M rounds
String x = (new StringBuffer()).append("Hello").append(",").append(" ").append(name).toString();
}
-------------------------------------------------------------------------------------------------------------------
To Test String is Empty
for (int i =0; i < loop; i++)
{
//10m loops
if (a != null && a.equals(""))
{
}
}
Better way is....
for (int i =0; i < loop; i++)
{
//10m loops
if (a != null && a.length() == 0)
{
}
}
-------------------------------------------------------------------------------------------------------------------
If two strings have the same length
String a = “abc”
String b = “cdf”
for (int i =0; i < loop; i++)
{
if (a.equalsIgnoreCase(b))
{
}
}
Better way is....
String a = “abc”
String b = “cdf”
for (int i =0; i < loop; i++)
{
if (a.equals(b))
{
}
}
-------------------------------------------------------------------------------------------------------------------
If two strings have different length
String a = “abc”
String b = “cdfg”
for (int i =0; i < loop; i++)
{
if (a.equalsIgnoreCase(b))
{
}
}
Better way is....
String a = “abc”
String b = “cdfg”
for (int i =0; i < loop; i++)
{
if (a.equals(b))
{
}
}
-------------------------------------------------------------------------------------------------------------------
Avoid Exception
Object obj = null;
for (int i =0; i < loop; i++)
{
try
{
obj.hashCode();
} catch (Exception e) {}
}
Better way is....
Object obj = null;
for (int i =0; i < loop; i++)
{
if (obj != null)
{
obj.hashCode();
}
}
-------------------------------------------------------------------------------------------------------------------
Eliminate Method Call
byte x[] = new byte[loop];
for (int i = 0; i < x.length; i++)
{
for (int j = 0; j < x.length; j++)
{
}
}
Better way is....
byte x[] = new byte[loop];
int length = x.length;
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
}
}
Comments