Reputation: 35692
Suppose I do a bubble sort example like the following in Java:
package testing;
public class bubbleSort {
public static void main(String a[]) {
int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };
System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
System.out.println("PAUSE");
}
public static void bubble_srt(int a[], int n) {
int i, j, t = 0;
for (i = 0; i < n; i++) {
for (j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
}
}
Is there a way to find out
(a) How much RAM the data structure for the array of elements consumes?
(b) If not - is there a way to compare how much RAM that process consumes compared to a vanilla HelloWorld?
package testing;
public class Testing {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Upvotes: 2
Views: 131
Reputation: 6738
Use this formula;
static long memoryUsed() {
return runtime.totalMemory() - runtime.freeMemory();
}
static final Runtime runtime = Runtime.getRuntime();
Upvotes: 0
Reputation: 115328
You have to profile your application to get the real memory usage. Try YourKit. Add pause to your application just before calling sort. Create memory snapshot before running the sort and after it finished and compare them.
Calling all GC will not bring you are "real" result. There are a lot of objects allocated by VM itself. The will be probably cleaned and you will get wrong picture.
Upvotes: 0
Reputation: 1984
You can use getRunTime()
to find the runtime of the current program. And totalmemory
property will help you find the memory used.
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
Upvotes: 1
Reputation: 533472
How much RAM the data structure for the array of elements consumes?
Not easily. It will be about 40-48 bytes long, which isn't worth worrying about.
If not - is there a way to compare how much RAM that process consumes compared to a vanilla HelloWorld?
At a guess, I would say your first example uses up to 100 KB more than the second. This is because there is allot going on behind the sense to load extra classes and turn int
values into String
which is most of the memory consumption. Your array is trivial by comparison.
In any case, 100 KB isn't worth worrying about either. In a desktop 100 KB costs less than 1 cents and is reusable.
Upvotes: 1