Should I declare variables outside or inside reusable methods?

(I use String as an example, but it can be replaced for Object> MB of memory)

do it quite a lot:

private static String mTempString = ""; private static void SomeMethod() { mTempString = "Whatever Result"; } 

Now my question is: if I wrote it like this:

 private static void SomeMethod() { String mTempString = "Whatever Result"; } 

and use it in a loop (which runs hundreds of times per second as an example), will Java know how to manage memory as an example? Will the memory be equally efficient. (Sorry, I cannot verify this myself at the moment)

which is more efficient in terms of memory (excluding the fact that they are small variables)

- edit --- There was a great article here that explains this http://www.cs.berkeley.edu/~jrs/4/lec/08

+6
source share
6 answers

I did my own test on this to see if the compiler actually creates a β€œnew” object with each iteration. The following are the results of the following code:

 private static long mStartedTime; public static void main(String args[]) { long TotalTime = 0; int NumberOfLoops = 7; for(int i = 0; i < NumberOfLoops; i++) { mStartedTime = System.currentTimeMillis(); for(float Index = 0; Index < 10000000; Index++) { test1("wewgwgwegwegwegsd veweewfefw fwefwef wfwefdwvdw wefwe wevwev etbe tbebetbetb evberve"); } System.out.println("Program took: " + String.valueOf(System.currentTimeMillis() - mStartedTime) + " to complete."); TotalTime += System.currentTimeMillis() - mStartedTime; } System.out.println("Average time taken: " + String.valueOf(TotalTime / NumberOfLoops)); } public static void test1(String THisIsText) { String Test = THisIsText; Test = Test.substring(1); } private static String mTempString; public static void test2(String THisIsText) { mTempString = THisIsText; mTempString = mTempString.substring(1); } 

They came out with different results, it seems that the transfer of variables on a local scale leads to a loss of performance:

I can only guess that the local variables of the method are removed, and this takes time, why does test1 take longer? (Can someone confirm this)

(After many tests)

Local area: average time: 1183

Class reusable variable: Average time: 1043

+1
source

Keep the scope of your variables as narrow as possible.

This is important for several reasons:

  • Readability. . If you use this variable in three different places with four different values ​​(go figure), it will be difficult for you to determine for what purpose this variable should be used to serve.

  • Mistakes . You reduce the number of errors that can occur in your application if you save one variable in one, well-defined area. Suppose you had this String, and you expected it to be some value in two methods, but it was something completely different.

  • Goal purpose. I mentioned this a bit in the readability section, but if you have a static variable that keeps changing, its target goal has become unclear. Typically, static methods and variables can be used regardless of the state of the object, so if the state of the object affects the value of the static variable, the intent is confused.

I would not worry about memory performance at the moment (unless you had string strings, but I would say that you need to worry about two things). *

*: First optimization rule: do not do this.
Second optimization rule (only experts!): Do not do this yet .

+9
source

In general, prefer to limit the scope of variables as much as possible. This simplifies code understanding, debugging, and refactoring.

In this case, the memory required for these variables in both cases is very small. Each variable is a reference to an object, not an object. A link can take only four bytes when used as a local variable.

+3
source

The volume of local variables should always be minimal.

if you need a variable outside the scope, it is better to declare a variable inside the scope. In this case, there is no difference in performance, but for best coding practice, it is recommended to declare a variable in the smallest possible area. See This Similar and Popular SO Question

Another scenario would be to use an immutable type instead of a string. Where there will be a slight difference in performance (very slight). The statement at the top will be very slightly better since you do not need to initialize the variable in each loop. But in the line, since it creates a new object every time, so this is not a problem in your case.

+1
source

Jvm should be able to determine that it is a constant, and optimize it if necessary, so you do not need to worry about any style.

In the case of arithmetic expressions, the JVM can perform continuous flexion optimization.

If you are only interested in strings, constant strings are stored inside the string pool.

As you know, strings in java are immutable.

Therefore, if you have persistent strings in java, they will be stored only once, and all links will point to this string object.

eg.

  String s = "a" + "bc"; String t = "ab" + "c"; System.out.println(s == t); 

returns true since t and s point to the same string object.

In addition, java classes have constant pools to which all constants like these move.

Essentially, the JVM is pretty smart, and I don't think any of these toy examples are better than any other, at least in terms of efficiency. Although, as the other answers mention, there are software development considerations that you probably should consider.

+1
source

If mTempString is a temporary variable needed only in someMethod() , then it must be declared as a local variable inside the method and is never a static member of your class. The reason is because you want to make sure that no one is interfering with your temporary variable.

If you declare it in a class, your code is more error prone because you cannot be sure who can change this variable.

In your example, the temporary variable is declared as a static field. This makes the code loose. If two different threads call the same method almost simultaneously, then the second method call will change the value of the temporary variable that affects the thread that calls the first call.

0
source

Source: https://habr.com/ru/post/945903/


All Articles