I was browsing through the Java code today and I noticed something.
int[] m = mag;
int len = m.length;
int[] xm = xInt.mag;
if (len != xm.length)
return false;
(This is in the BigInteger class, which can be found by unzipping src.zip. It's in the equals method.) Why is an entirely new variable m created when it is only used once? Why isn't the code just int len = mag.length? I saw this in another method also (bitLength), and again, m is only used once. Is there any advantage to doing this or is it just a mistake by the creators of this class?
Edit: as #usernametbd pointed out, it is used a bit later:
for (int i = 0; i < len; i++)
if (xm[i] != m[i])
return false;
But they still could have just used mag. Why would an entirely new variable be made?
In a different function (in the same class, bitLength), a new variable m is made and it's only used a single time.
Because mag is a field, m is local variable. Access to local variable may be faster, though modern JITs can create such a substitute local variable automatically.
BTW you should have tell what the method you had in mind (I found it to be equals()), and cite original source (it is available) rather than decompiled one.
A bit (few lines) futher down, they use
for (int i = 0; i < len; i++)
if (xm[i] != m[i])
return false;
So m isn't completely isolated. They certainly could've used mag instead, but it's just a design choice.
When you call length (public final member variable of Array) via reflection which is constant time operation. But it is not same in C++. You have to get first array size in bytes and after divide this result to size of int to get exact value(Maybe there is better way). I think developer has the same reflex from him C++ times and carried value into local variable to use several times.
Why is it important to you? The statement is not copying an array, just copying a reference -- a pointer. And "m" will likely be allocated into a register, whereas the JVM standard requires that "mag" must usually be refetched from the object -- the JITC can't freely optimize away field references.
Related
This question already has answers here:
The constructors Integer(int), Double(double), Long(long) and so on are deprecated
(1 answer)
create a new Integer object that holds the value 1?
(2 answers)
Closed 3 years ago.
I'm following a book by Walter Savitch called Absolute Java. A sample program in it contains the following lines:
Double[] d = new Double[10];
for (int i = 0; i < d.length; i++)
d[i] = new Double(d.length - i);
And I got the following warning message:
warning: [deprecation] Double(double) in Double has been deprecated
I believe that the warning message is telling me to replace the use of constructors since it is already deprecated, so what should I replace it with?
Explanation
You should replace it with:
d[i] = Double.valueOf(d.length - i);
From its Javadoc:
Deprecated.
It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance.
In general, valueOf is not forced to always return a new instance. It can utilize an internal cache and re-use values created before already, which makes it faster. For example if you create hundreds of 1.0.
Note
Is there a specific reason you are using a Double[] in the first place? If not, go for double[] instead. The primitives are much faster and have less memory overhead, compared to their object wrapper.
Then your code is just:
double[] d = new double[10];
for (int i = 0; i < d.length; i++)
d[i] = d.length - i;
By the way, you should prefer to never omitt the curly braces. Even if your loop is just one line. This is a very common source for bugs that are hard to find.
Also, your variable naming is not very good. What is d? Try to give it a name that reflects what it actually means. Like ages if it stores person ages, for example. If you do not have something specific, maybe use values. That is already better than just d. Especially since it is plural, so it is clear that it is an array of multiple values.
double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
values[i] = values.length - i;
}
From Java 9 constructor(s) method(s) was Deprecated
Deprecated. It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance.
Constructs a newly allocated Double object that represents the primitive double argument.
So replace with:
Double.valueOf(d.length - i)
I found this example code for Joshua Bloch's book, Effective Java. It's meant to demonstrate why you should avoid unnecessarily creating objects:
public class Sum {
private static long sum() {
Long sum = 0L;
for (long i = 0; i <= Integer.MAX_VALUE; i++)
sum += i;
return sum;
}
public static void main(String[] args) {
int numSets = Integer.parseInt(args[0]);
long x = 0;
for (int i = 0; i < numSets; i++) {
long start = System.nanoTime();
x += sum();
long end = System.nanoTime();
System.out.println((end - start) / 1_000_000. + " ms.");
}
// Prevents VM from optimizing away everything.
if (x == 42)
System.out.println();
}
}
What do the last two lines of the main method accomplish here?
That final comparison is the only usage of that variable. Without it, who would care about the value in that variable?
Nobody!
So, the compiler might assume: that value is never used, and the code that writes to it has node side effects. Things that don't get used, why waste time writing to them.
Thus: that final first "read" usages prevents over eager compilerd from "optimizing out" the call to the method you intend to measure!
The last two lines force the compiler to run the whole loop, to find the value of x. Otherwise it might detect that x is not being used at all and ignore the loop, given that inside of it no "real" work is being made. Even though sum() is called repeatedly, the result of accumulating its returned value would be discarded in the end if we do nothing with x.
Of course, this assumes that the println() statement inside the loop can be safely ignored, I'm unsure if the compiler can make such a decision. That would be one aggressive compiler!
The two last lines will make sure that the JVM doesn't remove calls that it could potentially consider no-ops otherwise, one option is to use the result - so you might sum all the return values and then display the sum at the end.
Another way to prevent vm from optimizing is to disable JIT:
-Djava.compiler=NONE
JIT:
When JVM compiles the class file, it doesn’t complete the full class
file; it compiles only a part of it on need basis. This avoids heavy
parsing of complete source code. This type of compilation is termed as
JIT or Just-In-Time compilation. JVM is Platform(OS) dependent Code
generation JIT is Platform Oriented, generates the native byte code,
so it is faster one than JVM :)
I am learning Java JNI and trying to understand the GetStringUTFChars & ReleaseStringUTFChars. Still i can't able to understand the ReleaseStringUTFChars.
As per my understanding from some article, in most cases that the GetStringUTFChars return a reference to the original string data and not a copy. So actually the ReleaseStringUTFChars release the jstring or the const char* (if copied) or both.
I can get a better understanding if i get the answer to the below question.
In the below code do i need to call the ReleaseStringUTFChars in a for loop or only once (with any one of the const char*)?
#define array_size 10
const char* chr[array_size];
jboolean blnIsCopy;
for (int i = 0; i < array_size; i++) {
chr[i] = env->GetStringUTFChars(myjstring, &blnIsCopy);
printf((bool)blnIsCopy ? "true\n" : "false\n"); //displays always true
printf("Address = %p\n\n",chr[i]); //displays different address
}
//ReleaseStringUTFChars with in a for loop or single statement is enough
for (int i = 0; i < array_size; i++) {
env->ReleaseStringUTFChars(myjstring, chr[i]);
}
Thanks in advance.
Get/ReleaseStringUTFChars must always be called in pairs, regardless of whether a copy or not is returned.
In practice, you pretty much always get a copy (at least with the JVM implementations I checked: OpenJDK and Dalvik) so that the GC is free to move the original array. It obviously can't collect it because you've got a reference to the string but it'll still move objects around.
There is also a GetStringCritical/ReleaseStringCritical call pair, which will always attempt to return a pointer to the original array (though in theory it may still return a copy). This makes it faster but it comes at a cost: the GC must not move the array until you release it. Again, in practice this is usually implemented by establishing a mutex with the GC, and incrementing a lock count for Get and decrementing it for Release. This means these must be called in pairs too, otherwise the lock count will never get back to zero and GC will probably never run. Please note: Get/ReleaseStringCritical also comes with other limitations which are less relevant to this question but are no less important.
The string called "code" doesn't seem to read. Why is that and how do I fix it?
My code (the snippet that causes problems):
String code;
for(int z = 0; z<x;z= z+0) // Repeat once for every character in the input string remaining
{
for(int y=0;y<2;y++) //Repeat twice
{
c = (char)(r.nextInt(26) + 'a'); //Generate a random character (lowercase)
ca = Character.toString(c);
temp = code;
code = temp + ca; //Add a random character to the encoded string
}
My error report:
--------------------Configuration: <Default>--------------------
H:\Java\Compiler.java:66: variable code might not have been initialized
temp = code;
^
1 error
Process completed.
(I am using JCreator 5.00, Java 7.)
(Yes, the error report looks stupid, but it Stack Overflow reads it as coding.)
What value would code have if x is zero? The answer is it would have no value at all (not even null). You could just initialize it to an empty string if you like:
String code = "";
Java requires that every variable is initialized before its value is used. In this example, there is a fairly obvious case in which the variable is used before it is assigned. The Java Language Spec (JLS) doesn't allow this. (If it did, the behaviour of programs would be unpredictable, including ... potentially ... JVM crashes.)
In other cases, the compiler complains when in fact the variable in question is always initialized (or so it seems). Rather than "understanding" your code, or trying to derive a logical proof of initialization, the compiler follows a specified procedure for deciding if the variable is definitely assigned. This procedure is conservative in nature, and the answer it gives is either "it is initialized" or "it might not be initialized". Hence the wording of the compilation error message.
Here is an example in which the compiler will complain, even though it is "obvious" that the variable is initialized before use:
boolean panic;
for (int i = 0; i < 10; i += 2) {
if (i % 2 == 1 && panic) { // compilation error here
System.out.println("Panic!!");
}
}
The definite assignment rules (specified in the JLS) say that panic is NOT definitely initialized at the point indicated. It is a simple matter for a person who understands the basics of formal methods to prove that i % 2 == 1 will always be false. However, the compiler can't. (And even if it could, the code is still in error given JLS rules.)
You've created a reference, but you've never initialized it. Initialize code by changing the first line to
String code = ""
Edit: Zavior pointed out that you can pull an initialized string from the cache rather than allocate space for a new one.
But why are you assigning temp to code and then code to temp plus something else? It can be set to code = code + ca.
I've read that in Java an object of type String can't change. But int and char variables can. Why is it? Can you give me an example?
Thank you.
(I am a newer -_- )
As bzabhi said, strings are immutable in Java. This means that a string object will never change. This does not mean you can not change string variables, just that you cannot change the underlying memory representation of the string. for an example:
String str = "Hello";
str += " World!";
Following the execution of these lines, str will point to a new string in memory. The original "Hello" string still exists in memory, but most likely it will not be there for long. Assuming that there are no extenuating circumstances, nothing will be pointing at the original string, so it will be garbage collected.
I guess the best way to put this would be to say that when line 2 of the example executes, a new string in memory is created from the concatenation of the original string and the string being added to it. The str variable, which is just a reference to a memory location, is then changed to point at the new variable that was just created.
I am not particularly knowledgeable on the point, but, as I understand it, this is what happens with all "non-primitive" values. Anything that at some point derives from Object follows these rules. Primitive values, such as ints, bools, chars, floats and doubles allow the actual value in memory to be changed. So, from this:
int num = 5;
num += 2;
the actual value in memory changes. Rather than creating a new object and changing the reference, this code sample will simply change the value in memory for the num variable.
As for why this is true, it is simply a design decision by the makers of Java. I'm sure someone will comment on why this was made, but that isn't something I know.
int and char can't change either. As with strings, you can put a different value into the same variable, but an integer itself doesn't change. 3 will always be 3; you can't modify it to be 4.
String is an immutable type (the value inside of it cannot change). The same is true for all primitive types (boolean, byte, char, short, int, long, float, and double).
int x;
String s;
x = 1;
x = 2;
s = "hello";
s = "world";
x++; // x = x + 1;
x--; // x = x - 1;
As you can see, in no case can you alter the constant value (1, 2, "hello", "world") but you can alter where they are pointing (if you warp your mind a bit and say that an int variable points at a constant int value).
I'm not sure that it is possible to show (by example) that Strings cannot change. But you can confirm this by reading the description section of Javadoc for the String class, then reading the methods section and noting that there are no methods that can change a String.
EDIT: There are many reasons why Strings are designed to be immutable in Java. The most important reason is that immutable Strings are easier to use correctly than mutable ones. And if you do need the mutable equivalent of a String for some reason, you can use the StringBuilder (or StringBuffer) class.
It's also worthwhile to note that since strings are immutable, that if they are passed into a method, they can't be modified inside of the method and then have those changes seen outside of the method scope.
public void changeIt(String s) {
// I can't do anything to s here that changes the value
// original string object passed into this method
}
public void changeIt(SomeObject o) {
// if SomeObject is mutable, I can do things to it that will
// be visible outside of this method call
}
This little article can probably explain it better than I can: http://www.jchq.net/tutorial/09_02Tut.htm
Strings are immutable in java. Nevertheless, you can still append or prepend values to strings. By values, I mean primitive data types or other strings.
However, a StringBuffer is mutable, i.e. it can be changed in memory (a new memory block doesn't have to be allocated), which makes it quite efficient. Also, consider the following example:
StringBuffer mystringbuffer = new StringBuffer(5000);
for (int i = 0; i<=1000; i++)
{
mystringbuffer.append ( 'Number ' + i + '\n');
}
System.out.print (mystringbuffer);
Rather than creating one thousand strings, we create a single object (mystringbuffer), which can expand in length. We can also set a recommended starting size (in this case, 5000 bytes), which means that the buffer doesn't have to be continually requesting memory when a new string is appended to it.
While a StringBuffer won't improve efficiency in every situation, if your application uses strings that grow in length, it would be efficient. Code can also be clearer with StringBuffers, because the append method saves you from having to use long assignment statements.