I have a method in java  Public Object someMethod (String param) ( //some calculations Return Object )   I want to test the performance of this method ( how much time would it take to reach to db and return an object )  How can I do this?  I don't have a main method because its a library. I use unit tests to check if it works.  Help.
27793
How do I get a method's execution time?   Is there a Timer utility class for things like timing how long a task takes, etc?     Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.
1905
I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.   Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.  Anyhow -   I was developing a basic shopping cart which could contain an ArrayList of Book objects. In order to implement the addBook(), removeBook(), and hasBook() methods of the Cart, I wanted to check if the Book already existed in the Cart. So off I go -  public boolean equals(Book b) {     ... // More code here - null checks     if (b.getID() == this.getID()) return true;     else return false; }   All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much.  Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following:  public boolean hasBook(int i) {     Book b = new Book(i);     return hasBook(b); }  public boolean hasBook(Book b) {     // .. more code here     return this.books.contains(b); }   All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following:  public boolean equals(Object o) {     Book b = (Book) o;     ... // The rest goes here    }   Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly  was  a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?
43
I am working on an application and one design approach involves extremely heavy use of the instanceof operator. While I know that OO design generally tries to avoid using instanceof, that is a different story and this question is purely related to performance. I was wondering if there is any performance impact? Is is just as fast as ==?  For example, I have a base class with 10 subclasses. In a single function that takes the base class, I do checks for if the class is an instance of the subclass and carry out some routine.   One of the other ways I thought of solving it was to use a "type id" integer primitive instead, and use a bitmask to represent categories of the subclasses, and then just do a bit mask comparison of the subclasses "type id" to a constant mask representing the category.  Is instanceof somehow optimized by the JVM to be faster than that? I want to stick to Java but the performance of the app is critical. It would be cool if someone that has been down this road before could offer some advice. Am I nitpicking too much or focusing on the wrong thing to optimize?
7437
I have a method that uses the  function and makes a call to another method. On initial load method 2 works fine. However, after the timeout, I get an error that says method2 is undefined. What am I doing wrong here?  ex:  test.prototype.method = function() {     //method2 returns image based on the id passed     this.method2('useSomeElement').src = "http://www.some.url";     timeDelay = window.setTimeout(this.method, 5000); };  test.prototype.method2 = function(name) {     for (var i = 0; i &lt; document.images.length; i++) {         if (document.images[i].id.indexOf(name) &gt; 1) {             return document.images[i];         }     } };
112004
I have a Linq query that I want to call from multiple places:  var myData = from a in db.MyTable              where a.MyValue == "A"              select new  {                             a.Key,                             a.MyValue                           };   How can I create a method, put this code in it, and then call it?  public  ???  GetSomeData() {    // my Linq query }
43400
So far I've been using public void run() {} methods to execute my code in Java. When/why might one want to use main() or init() instead of run()?
5127
The method signature of a Java main() method is:  public static void main(String[] args){     ... }   Is there a reason for this method to be static?
18114
I have a method with an out parameter that tries to do a type conversion. Basically:  public void GetParameterValue(out object destination) {     object paramVal = "I want to return this. could be any type, not just string.";      destination = null; // default out param to null     destination = Convert.ChangeType(paramVal, destination.GetType()); }   The problem is that usually someone would call this like:  string output; GetParameterValue(output);   This will fail because of:  destination.GetType()   destination is null, so we can't call .GetType() on it. We also can not call:  typeof(destination)   because destination is a variable name not a type name.  So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.    Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that DbParameter.Value is of type object.  What would be ideal would be for the developers to do something like:  string val = GetParameterValue("parameterName");   The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with:  string val; GetParameterValue("parameterName", out val);   And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method:  public T GetParameterValue&lt;T&gt;(string paramName)   So the developers can do:  string val = GetParameterValue&lt;string&gt;("parameterName");   I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM):  MyObj.SomeProp = GetParameterValue&lt;MyObj.SomeProp.GetType()&gt;("parameterName");   But again, if MyObj.SomeProp is null, that .GetType() call fails. The VM has to know the type of MyObj.SomeProp, even when its null, right? or else how would it catch cast exceptions?    To partially solve my own problem, I can do:  MyObj.SomeProp = GetParameterValue&lt;typeof(MyObj).GetField("SomeProp").GetType()&gt;("parameterName");   The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (MyObj.SomeProp) and in the DB. There has to be a better way...
70083
I'm trying to find out how much memory my objects take to see how many of them are ending up on the  (which is anything over 85,000 bytes). Is it as simple as adding 4 for an int, 8 for a long, 4 (or 8 if you're on 64 bit) for any reference types etc for each object, or are there overheads for methods, properties, etc.?
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
8436
What is the best way to unit test a method that doesn't return anything? Specifically in c#.  What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.
81333
Is there any performance reason to declare method parameters final in Java?  As in:  public void foo(int bar) { ... }   Versus:  public void foo(final int bar) { ... }   Assuming that bar is only read and never modified in foo().
73774
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?  Say I have the method:    writeToStream(Object o, OutputStream out)   Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.  I'm considering writing a class like this (untested):  class StringOutputStream extends OutputStream {    StringBuilder mBuf;    public void write(int byte) throws IOException {     mBuf.append((char) byte);   }    public String getString() {     return mBuf.toString();   } }   But is there a better way? I only want to run a test!
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:
382
I'm reviewing some code for a friend and say that he was using a return statement inside of a try-finally block.  Does the code in the Finally section still fire even though the rest of the try block doesn't?  Example:  public bool someMethod() {   try   {     return true;     throw new Exception("test"); // doesn't seem to get executed   }   finally   {     //code in question   } }
26472
We have an object (let's call it Child) with a formula field that does a lot of checking of various fields and spits out a numeric result (estimated number of days some work will take, based on a bunch of flags and conditions).  Another object (Parent) has multiple Children related to it through a lookup.   I wrote an apex class that aggregates the Children of a Parent in various ways based on several fields, including the formula result. I now want to test that logic, but when I try to create some sample Children to feed into my test, I'm told that I can't write to formula fields.  I don't want to figure out how to build a tree of objects and set specific fields to get the value I want to test from the formula field. Furthermore, the formula has a limited set of results, which may change in the future (say, the business decides that some particular type of work takes 8 days instead of 10). I want to test various edge cases that the formula can't produce today.   What's the best approach to this?
24824
Consider type like this one  public interface IHaveGenericMethod {    T1 Method&lt;T1&gt;(T1 parm);    T2 Method&lt;T1,T2&gt;(T1 parm);    int Method2(int parm); }   How do I get a methodInfo for its methods? for a regular non-generic method, like method2, I can go with  typeof(IHaveGenericMethod).GetMethod("methodName",new Type[]{typeof(itsParameters)});   for a generic method though, I can't, since it's parameters are not types per-se. So, how do I do that? I know that I can call  typeof(IHaveGenericMethod).GetMethods()   to get all methods of that type, and then iterate over that collection and do some matching, but it's ugly. Is there a better way?