I was testing the performance of two different approaches to handling streams of integers (primitives).  To my surprise, the first test case is always slower, no matter the order.  public void intStreamTest() {     final int[] ints = new int[1000];     for (int x = 0; x &lt; 1000; x++) {         ints[x] = new Random().nextInt(1000);     }     // T1     long start = System.currentTimeMillis();     for (int x = 0; x &lt;= 10000; x++) {         List&lt;Integer&gt; result =             IntStream.of(ints).boxed().collect(Collectors.toList());     }     System.out.println("T1 " + (System.currentTimeMillis() - start));     // T2     long start2 = System.currentTimeMillis();     for (int x = 0; x &lt;= 10000; x++) {         List&lt;Integer&gt; result =             IntStream.of(ints).mapToObj(Integer::valueOf).collect(Collectors.toList());     }     System.out.println("T2 " + (System.currentTimeMillis() - start2)); }   Here is an example of the output:  T1 150 T2 95   When I change the order of test cases (swap sections T2 and T1) I get:  T2 153 T1 92   Did I make a mistake? How is it possible that a second test case is always faster (approx by 60%)?
915
How do you write (and run) a correct micro-benchmark in Java?  I'm looking for some code samples and comments illustrating various things to think about.  Example: Should the benchmark measure time/iteration or iterations/time, and why?  Related:
66573
I know that in JavaScript, creating a for loop like this: for(int i = 0; i &lt; arr.length; i++) is costly as it computes the array length each time. Is this behavior costly in c# for lists and arrays as well. Or at compile-time is it optimized?  Also what about other languages such as Java, how is this handled?
95854
I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview questions:  Write a method that takes an int array of size m, and returns (True/False) if the array consists of the numbers n...n+m-1, all numbers in that range and only numbers in that range. The array is not guaranteed to be sorted. (For instance, {2,3,4} would return true. {1,3,1} would return false, {1,2,4} would return false. The problem I had with this one is that my interviewer kept asking me to optimize (faster O(n), less memory, etc), to the point where he claimed you could do it in one pass of the array using a constant amount of memory. Never figured that one out.  Along with your solutions please indicate if they assume that the array contains unique items. Also indicate if your solution assumes the sequence starts at 1. (I've modified the question slightly to allow cases where it goes 2, 3, 4...) edit: I am now of the opinion that there does not exist a linear in time and constant in space algorithm that handles duplicates. Can anyone verify this? The duplicate problem boils down to testing to see if the array contains duplicates in O(n) time, O(1) space. If this can be done you can simply test first and if there are no duplicates run the algorithms posted. So can you test for dupes in O(n) time O(1) space?
118496
I want to sort a list of objects of a class by 2 ways. I am able to do custom sort by overwriting the compareTo method.  But I have two lists and I want to sort them differently.  Can I still accomplish this by calling the list.sort() method?  global class myClass implements Comparable{      public integer Total{get;set;}     public integer numOfDays{get;set;}      global Integer compareTo(Object compareTo) {         myClass compareToEmp = (myClass)compareTo;         if (Total == myClass.Total) return 0;         if (Total &gt; myClass.Total) return 1;         return -1;             } }   In the above example, how can I also be able to sort by "numOfDays"?  //UPDATE:  I actually wanted to sort list by single property.   But use different properties to sort different lists.  I ended up adding a new field to my class for sorting purpose.  global class myClass implements Comparable{      public integer Total{get;set;}     public integer numOfDays{get;set;}     public boolean isA {get;set;}      global Integer compareTo(Object compareTo) {         myClass compareToEmp = (myClass)compareTo;         if(isA){          if (Total == myClass.Total) return 0;         if (Total &gt; myClass.Total) return 1;             return -1; }         else{              if (Total == myClass.numOfDays) return 0;         if (Total &gt; myClass.numOfDays) return 1;             return -1;          }            } }
6702
Which is the fastest algorithm to find out prime numbers using C++? I have used sieve's algorithm but I still want it to be faster!
13369
I have an Object[] array, and I am trying to find the ones that are primitives. I've tried to use Class.isPrimitive(), but it seems I'm doing something wrong:  int i = 3; Object o = i;  System.out.println(o.getClass().getName() + ", " +                    o.getClass().isPrimitive());   prints java.lang.Integer, false.  Is there a right way or some alternative?
92088
public class WrapperTest {      public static void main(String[] args) {          Integer i = 100;         Integer j = 100;          if(i == j)             System.out.println("same");         else             System.out.println("not same");     }     }   The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
61
I need to find a bottleneck and need to accurately as possible measure time.  Is the following code snippet the best way to measure the performance?  DateTime startTime = DateTime.Now;  // Some execution process  DateTime endTime = DateTime.Now; TimeSpan totalTimeTaken = endTime.Subtract(startTime);
108583
Does anyone know the major differences between the Java and .Net garbage collectors? A web search has not revealed much, and it was a question that came up in a test.
40009
I have the following code that shows either a bug or a misunderstanding on my part.  I sent the same list, but modified over an ObjectOutputStream.  Once as [0] and other as [1].  But when I read it, I get [0] twice.  I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.  Is this work as it should, or should I file a bug?   import java.io.*; import java.net.*; import java.util.*;  public class OOS {      public static void main(String[] args) throws Exception {         Thread t1 = new Thread(new Runnable() {             public void run() {                 try {                     ServerSocket ss = new ServerSocket(12344);                     Socket s= ss.accept();                      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());                     List same = new ArrayList();                     same.add(0);                     oos.writeObject(same);                     same.clear();                     same.add(1);                     oos.writeObject(same);                  } catch(Exception e) {                     e.printStackTrace();                 }             }         });         t1.start();          Socket s = new Socket("localhost", 12344);         ObjectInputStream ois = new ObjectInputStream(s.getInputStream());          // outputs [0] as expected         System.out.println(ois.readObject());          // outputs [0], but expected [1]         System.out.println(ois.readObject());         System.exit(0);     } }
29737
I'm writing an application which reads large arrays of floats and performs some simple operations with them. I'm using floats, because I thought it'd be faster than doubles, but after doing some research I've found that there's some confusion about this topic. Can anyone elaborate on this?
110922
Or is it now the other way around?  From what I've heard there are some areas in which C# proves to be faster than C++, but I've never had the guts to test it by myself.  Thought any of you could explain these differences in detail or point me to the right place for information on this.
88076
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.  Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?  /// &lt;summary&gt; /// Compare property values (as strings) /// &lt;/summary&gt; /// &lt;param name="obj"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public bool PropertiesEqual(object comparisonObject) {      Type sourceType = this.GetType();     Type destinationType = comparisonObject.GetType();      if (sourceType == destinationType)     {         PropertyInfo[] sourceProperties = sourceType.GetProperties();         foreach (PropertyInfo pi in sourceProperties)         {             if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null &amp;&amp; destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))             {                 // if both are null, don't try to compare  (throws exception)             }             else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))             {                 // only need one property to be different to fail Equals.                 return false;             }         }     }     else     {         throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");     }      return true; }
13449
I can't understand where the final keyword is really handy when it is used on method parameters.    If we exclude the usage of anonymous classes, readability and intent declaration then it seems almost worthless to me.   Enforcing that some data remains constant is not as strong as it seems.    If the parameter is a primitive then it will have no effect since the parameter is passed to the method as a value and changing it will have no effect outside the scope.  If we are passing a parameter by reference, then the reference itself is a local variable and if the reference is changed from within the method, that would not have any effect from outside of the method scope.    Consider the simple test example below. This test passes although the method changed the value of the reference given to it, it has no effect.  public void testNullify() {     Collection&lt;Integer&gt; c  = new ArrayList&lt;Integer&gt;();           nullify(c);     assertNotNull(c);            final Collection&lt;Integer&gt; c1 = c;     assertTrue(c1.equals(c));     change(c);     assertTrue(c1.equals(c)); }  private void change(Collection&lt;Integer&gt; c) {     c = new ArrayList&lt;Integer&gt;(); }  public void nullify(Collection&lt;?&gt; t) {     t = null; }
3046
Assuming I have an ArrayList  ArrayList&lt;MyClass&gt; myList;   And I want to call toArray, is there a performance reason to use  MyClass[] arr = myList.toArray(new MyClass[myList.size()]);   over  MyClass[] arr = myList.toArray(new MyClass[0]);   ?  I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.  Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.