Monday, April 07, 2008

Primitives vs Objects

At times we come across a situation when we need to decide whether to use primitive types or wrapper objects for numeric values in Java. The wrapper classes come in handy when we need to pass on the null values, which can't be achieved with primitive types as they are always initialized to their respective default values.

The general concept is that primitive types are far more efficient then using wrapper classes in terms of memory usage and time taken for creating the data types. For one of my project I need to decide which one to use, so I thought about measuring the cost difference between these two options. I wrote a simple class which creates n number of objects of a class either having primitives or wrapper classes. The code is given below-

import java.util.ArrayList;
import java.util.List;

public class ObjectVsPrimitive {

List<WrapperNumbers> wrappers;
List<PrimitiveNumbers> primitives;

public void testWrapper(int count) {
wrappers = new ArrayList<WrapperNumbers>();
for (int i = 0; i <= count; i++)
wrappers.add(new WrapperNumbers());
}

public void testPrimitive(int count) {
primitives = new ArrayList<PrimitiveNumbers>();
for (int i = 0; i <= count; i++)
primitives.add(new PrimitiveNumbers());
}

public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java ObjectVsPrimitive 'P' (or 'O') <some number>");
System.exit(-1);
}

int count = 0;

try {
count = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number.");
System.exit(-1);
}

ObjectVsPrimitive test = new ObjectVsPrimitive();
StopWatch watch = new StopWatch();

if (args[0].equalsIgnoreCase("p"))
test.testPrimitive(count);
else
test.testWrapper(count);

watch.stop();
double freeMem = Runtime.getRuntime().freeMemory() / 1024 / 1024;
double totalMem = Runtime.getRuntime().totalMemory() / 1024 / 1024;
System.out.println("Time taken: " + watch.time() + " seconds");
System.out.println("Total Memory: " + totalMem + "MB, Free Memory: " + freeMem + " MB"
+ ", Used Memory: " + (totalMem - freeMem) + "MB");
}

/**
* A class having primitives for holding numeric values.
*/
@SuppressWarnings("unused")
public class PrimitiveNumbers {
private short SHORT = 10;
private int INT = 10;
private long LONG = 10l;
private double DOUBLE = 10.0d;
private float FLOAT = 10.0f;
}

/**
* A class having wrapper classes for holding numeric values.
*/
@SuppressWarnings("unused")
public class WrapperNumbers {
private Short SHORT = new Short((short) 10);
private Integer INT = new Integer(10);
private Long LONG = new Long(10l);
private Float FLOAT = new Float(10.0f);
private Double DOUBLE = new Double(10.0d);
}

/**
* Simple class to measure time.
*/
static class StopWatch {
private long start;
private long stop;

public StopWatch() {
start();
}

/** Starts timer */
public final void start() {
this.start = System.currentTimeMillis();
this.stop = 0;
}

/** Stops timer */
public void stop() {
this.stop = System.currentTimeMillis();
}

/** Returns time taken in seconds */
public double time() {
return (stop - start) / 1000.0;
}
}
}
A test run for creating 1 million objects of the class having primitives consumed 52MB of RAM while class having wrappers consumed a whooping 111MB, which is more then twice over the primitives.

Memory (MB)

Creation of 1 million objects of the class having primitives took 0.77 seconds while class having wrappers took 2.64 seconds, which is around 3.5 times over the primitives.

Time (seconds)

If one looks at the comparative results and calculates it in percentage terms then obviously choice will be primitives. If we think deeply then using wrappers may make sense, if there is a requirement. Think does your application will ever need 1 million objects in memory at the same time or do you need to create 1 million objects within couple of seconds only? If this is not the case then use the wrappers without worrying much about the performance cost.

Monday, November 19, 2007

Monitor SOAP messages

While developing Web Services at times one has to look for what is going out and coming in during web service interaction. Eclipse has a built-in TCP/IP Monitor but somehow I did not have a good experience using it.

Apache SOAP project has small utility called TCP Tunnel/Monitor, which is available here. TCP Tunnel/Monitor can be started using follwing command-

set CLASSPATH=%CLASSPATH%;./soap.jar;
java org.apache.soap.util.net.TcpTunnelGui 80 localhost 8080

Here first option 80 is the port where TcpTunnel will listen on your machine (localhost). The second parameter is the target address (the local machine in this case). The final parameter 8080 is the port where it will forward the calls to desired server as specified in 2nd parameter.

The TCP Tunnel/Monitor application is really just a simple proxy application that includes a visual interface to view the request response XML. TCP Tunnel/Monitor will display a window with two text areas:




* The text area on the left shows the request.
* The text area on the right shows the response received from the target server.

Tuesday, September 04, 2007

Struts 2 does not like mathematical operators in attribute names

If mathematical operators (+, -, *, /) are made part of an attribute name then Struts 2 may mis-interpret them during lookups. Say if one uses "user-name" as attribute name for storing an object in request scope. On attempt of retrieving this variable from request scope using-

request.getAttribute("user-name");

if Struts 2 does not find this variable in request scope then it looks in ValueStack using OGNL. The OGNL interprets "user-name" as an expression something like ${user - name} and looks for two attributes "user" & "name" and returns difference of value of "user" and "name". This will lead to ClassCastException in your code when you do something like-

User user = (User) request.getAttribute("user-name");

because Struts 2 will return a BigInteger.

Moral of the story, never use mathematical operators in attribute names at least with Struts 2 and of course with JSTL also.