which is faster, creating new variable vs reusing old variable? - java

which is faster creating new variable or reusing old one for java programming language?
example
case 1: creating
int x = 5;
int var = 1;
case 2: reusing old one
int x = 5;
x = 1;

"Which is faster?" is the wrong question. "Which is correct for the algorithm?" is the right question.
As a rule, you only reuse a variable if it needs to hold a new primitive value or point to a different object, because it is the variable that represents the current state. If the variable is reassigned to hold something that means something different, you should not do that but use a new variable.
So sum += item; is a valid reuse of the variable sum. But
foo = 42;
buyQuantity(foo);
...
foo = 23;
sendMessages(foo);
is not a valid reuse of foo.
A related but different question is whether you should reuse an object to hold new values. Not usually. For example:
Foo foo = new Foo();
for (int ix = 0; ix < MAX_ITERS; ++ix )
{
foo.clear();
foo.fill();
process(foo);
}
is worse than:
for (int ix = 0; ix < MAX_ITERS; ++ix )
{
Foo foo = new Foo();
foo.fill();
process(foo);
}

I did an small and simple test: Running a loop on a large (10 million) array and fill each element with a number.
Test1 : define a var before the loop and use that
Test2 : define a const inside the loop
To make the test as honest as possible, all other operations were removed.
Code
//#ts-nocheck
const maxInt = 10000000
// fill Array with a number
let A = [...Array(maxInt)].map(x => 10);
// Test 1 : Variable declared before
let x
console.time('test1')
B = A.map((a) => {
x = 3
return x
})
console.timeEnd('test1')
// Test 2 : Const variable declared in the Loop, every time
console.time('test2')
C = A.map((a) => {
const x = 3
return x
})
console.timeEnd('test2')
Test results
The test was run multiple times and on avarage (not calculated) the results were:
test1: 190.656ms
test2: 282.766ms
(Running on a Macbook with enough memory and normal CPU)
My careful conclusion: Creating a Const every time does have a slight performance impact.

Related

Scope of variable instantiated inside a method - Java

Is this code safe in Java?
public class HelloWorld {
public static void main (String args[]) {
HelloWorld h = new HelloWorld();
int y = h.getNumber(5);
int z = h.getNumber (6);
if (y == 10)
System.out.println("true");
}
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
}
My co-worker says that int number will be placed on the stack and when getNumber returns it will be popped off and could potentially be overwritten.
Is the same code potentially unsafe in C?
The HelloWorld class has no fields, and is therefore immutable. You can call your getNumber(x) function as many times as you'd like, from any thread, using the same object, and it will always give the same result for the same argument.
Maybe your co-worker is recalling horror stories in C where you can have something like static int number, which "belongs" to the method and which would get overwritten. Or maybe she's thinking about "return by reference"; even if it were, you'd be referencing a brand-new object every time because number is newly instantiated for every method call.
Your coworker is correct, sort of, but they apparently misunderstand what is going on.
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
Yes the value of 5 + 5 or 5 + 6 will be placed on the stack, but there is no danger of them being overwritten, they will properly be placed into y or z.
I suspect the confusion is from C (this type code works fine in C as well), but for pointers instead of primitives. Returning a result of malloc from a function in C can be "challenging" if you don't do it right.

Objects and Strings equality and memory digrams

I have having a bit of trouble understanding the difference between these two:
Suppose we have:
String x = "Test";
String y = x;
y = "Not Test"; //x is not modified here
The memory diagram for these two steps is the following:
x-> "Test"
x-> "Test" <-y
x-> "Test" y-> "Not Test"
But, consider class A with field 'int var':
A a = new A();
A b = a;
b.var = 5;
Here, if we modify b.var, a.var also changes to 5. Why is this different from the above case with strings?
Additionally, I would appreciate it if someone wouldn't mind explaining these memory diagrams for strings and objects. Would the result be different if a and b were objects of different classes set equal? Thanks.
There's a difference between
b.var = 5;
and
b = new A();
The second statement is similar to what you do in your first snippet, since y = "Not Test"; makes y refer to a new instance.
The first statement updates the state of the instance referred by both a and b, so both are affected.
Here's a diagram that shows your second snippet :
a -> object of class A <- b
containing an int
variable `var`
var <- 5
Both a.var and b.var contain 5, since they are the same variable.
Because String is Immutable class, state of which class can not be changed. While A is mutable because you changed it's state by changing value of variable. Secondly, both a and b are referencing to the same memory location and changing state of one will get reflected in second one but that's not the case in case of String if String a and b is Test changing a to Test1 will not change the Test to Test1 but it will create new String Test1 and assign it to a.
In the second case they are both pointing at the same place in the memory.
A a = new A(); a-->[MEMORY SPOT NR1]
A b = a; a-->[MEMORY SPOT NR1] AND b-->[MEMORY SPOT NR1]
b.var = 5; a-->[MEMORY SPOT NR1] AND b-->[MEMORY SPOT NR1]
and the value in var in [MEMORY SPOT NR1] is 5,
so both a.var and b.var take the value 5

issues with clone and for loop

private void buildDeck(ArrayList<Card> Monsters, ArrayList<Card> Spells) {
int monstersQouta = 15;
int spellsQouta = 5;
Random r = new Random();
for (; monstersQouta > 0; monstersQouta--) {
int randomIndex = r.nextInt(monsters.size());
MonsterCard monster = (MonsterCard) monsters.get(randomIndex);
MonsterCard clone = new MonsterCard(monster.getName(),
monster.getDescription(), monster.getLevel(),
monster.getAttackPoints(), monster.getDefensePoints());
clone.setMode(monster.getMode());
clone.setHidden(monster.isHidden());
clone.setLocation(Location.DECK);
deck.add(clone);
}
I need to know why we used here clone()
and how this for loop in this code works
As Andy Turner said for your first question :
clone() is not being used. It just so happens that the variable is called clone, but that has no semantic importance to the code.
Concerning the for statement he's composed of 3 parts ,each separated by one ; , and none of them is obligated to be there :
The first part is where you can, or not, declare your incremental variable : int i = 0;
The second part is where you must put an evaluation resulting on a boolean value : kappa.lengh >= i;
The thrid part is where you will modify the variable(s) values : i--;
Since none of these parts are obligated, you could write a correct for loop like this one : for(;;).
Here's a link to the documentation : For statement.

Pass-by-value vs. pass-by-reference in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is Java “pass-by-reference”?
I am trying to understand the difference between the 2 Java programs written below:
public class Swapping {
public static void main(String[] args) {
IntWrap i = new IntWrap(10);
IntWrap j = new IntWrap(20);
swap(i, j);
System.out.println("i " + i.i + ", j " + j.i);
}
public static void swap(IntWrap i , IntWrap j){
int x = i.i;
i.i = j.i;
j.i = x;
System.out.println("i " + i.i + ", j " + j.i);
}
}
public class IntWrap {
int i;
public IntWrap(int i){
this.i = i;
}
}
Output :
i 20, j 10
i 20, j 10
And second one:
public class Swapping {
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i " + i + ", j " + j);
}
public static void swap(Integer i , Integer j){
Integer temp = new Integer(i);
i = j;
j = temp;
System.out.println("i " + i + ", j " + j);
}
}
Output :
i 20, j 10
i 10, j 20
I am not able to understand that I even though I am passing the Integer object, it should get swapped in the original program. What difference did it created if I wrote the wrapper class on the top of it as I am again passing the object only.
All method parameters, including object references, are passed by value in Java. You can assign any value to the method parameter - the original value in the calling code will not be modified. However you can modify the passed object itself and the changes will persist when the method returns.
There are old Holder classes in J2SE API, specially designed to support calls to methods with "returnable parameters" (IntHolder or StringHolder, for instance). They are mostly used with generated code from IDL language as IDL requires support for in, out and inout parameters. These holders are very uncommon in other code.
You can also simulate passing by reference by using arrays:
String [] a = new String[1]; String [] b = new String[1];
void swap(String [] a, String [] b) {
String t = a[0]; a[0] = b[0]; b[0] = t;
}
Java uses call-by-value to pass all arguments.When you pass the object to a function, the object reference(address of object) gets passed by value.In the second program swap, you are assigning i=j and j=temp.
So i=address of 20
j=address of 10(new object)
But after return from swap, in the main program i is still pointing to 10 and j is pointing to 20.Thats why you are getting 10 and 20 back in main program.
But in first program, you are passing the address of your objects to swap function and in the swap function you are modifying the content of object pointed by these addresses.That is why, it is getting reflected in main method.
Ups. Integer objects are immutable in Java. You can not change their internal values neither from other method, neither at all. Only create new Integer object.
(If you don't know about pointers and references I suggest you go over them a bit, then the world will make more sense - Intro to Pointers)
Putting it down to the most simplest explanation, there are 2 ways java passed everything back and forth:
Pass-by=Value: Used for immutable objects (String, Integer, Double, etc.). These values cannot change with one exception, if you recreate the object.
String x = "World"; <- String x = new String("World");
x = "Hello"; <- x = new String("Hello");
x = x + " World"; <- x = new String("Hello" + " World");
printOutString(x); <- printOutString("Hello World");
Held at one memory location. Any alteration creates a new object with no relation to the previous and look at a separate memory location.
Pass-by-reference: Used for non-immutable objects (Classes, int, double, etc.). These values can be changed and still keep their old place in memory.
int i = 1;
i = 2; <- value at <reference-to-memory-as-value> = 2;
i = i + 1; <- value at <reference-to-memory-as-value> + 1;
printOutInteger(i); <- printOutInteger(value at <reference-to-memory-as-value>);
Any change to this object is done to the memory location. Therefore the location never changes (unless you create a new object).
The same is happening in your programs. The objects that say one thing in the method, then revert to the previous values. You are, in a way, Operator Overloading. You assign new values to the objections (Integer in this case) that you are sending, BUT you have passed the values which means Integer i within the method, because Integer is immutable, is looking at a different memory location to the Integer i in the main method. Therefore, when the method exits, the objects you passed are disposed of and Integer i and j now look at their original memory locations.
When you passed the classes with the int objects, as they are NOT immutable the memory locations were passed (by value) and the values at those locations were worked with. That is why the changes here were shown in the original objects.
I hope this helps

Generating sum of minterms in java

How can I generate the sum of minterms (boolean algebra) in java? We can generate sum of minterms throw ANDing with (X+X'). The following example explains the algorithm for a function with three variables A,B and C:
F(A,B,C)= A + B´*C
= A*(B+B´) + B´*C
= A*B + A*B´ + B´*C
= A*B*(C+C´) + A*B´*(C+C´) + B´*C*(A+A´)
= A*B*C+A*B*C´+A*B´*C+A*B´*C´+B´*C*A+B´*C*A´
= A*B*C+A*B*C´+A*B´*C+A*B´*C´+A*B´*C+A´*B´*C
The method in java looks like this:
String generateSumOfMinterms(String termsOfTheFunction, String variables){}
// Examples for functions with 2 variables A,B
generateSumOfMinterms("A", "A,B"){
//The result should looks like this
return "A*B+A*B'";
}
generateSumOfMinterms("A+B'", "A,B"){
//The result should looks like this (repeated terms are ok for example A*B')
return "A*B+A*B'+A'*B'+A*B'";
}
// Example for a function with 3 variables A,B,C
generateSumOfMinterms("A", "A,B,C"){
//The result should looks like this
return "A*B*C+A*B*C'+A*B'*C+A*B'*C'";
}
I have tried the following:
public List<Minterm> completeMinterm(Minterm minterm, String variables){
List<Minterm> minterms=new ArrayList<Minterm>();
minterms.add(minterm);
Minterm m1=new Minterm();
Minterm m2=new Minterm();
for (int k = 0; k < minterms.size(); k++) {
//A AB--> AB+AB'
for (int i = 0; i < variables.length(); i++) {
boolean varInMinterm=false;
for (int j = 0; j < minterms.get(k).atoms.size(); j++) {
if(minterms.get(k).atoms.get(j).variable==variables.charAt(i)){
varInMinterm=true;
break;
}
}
if(!varInMinterm){
varInMinterm=false;
m1= minterms.get(k);
m1.addAtom(new Atom(variables.charAt(i),false));
m2 = minterms.get(k);
m2.addAtom(new Atom(variables.charAt(i),true));
minterms.remove(k);
minterms.add(m1);
minterms.add(m2);
k=0;
}
}
}
I used eclipse debugger to find errors, I don't understand, why the atom added to m2 is added to m1 too in the same time, when this line is run:
m2.addAtom(new Atom(variables.charAt(i),true));
Here is an outline of a possible approach: First, you should create a more convenient representation of the expression - for example, the expression could be a list of instances of a Minterm class, and Minterm could contain a list of instances of an Atom class, each of which could contain a char that tells which variable it is and a boolean that tells whether the variable is negated or not. The first thing you should do is to loop through termsOfTheFunction and create such objects that represent the expression. Then, you can loop through the minterms, and every time you see a minterm that is missing one variable, you can remove it from the list and add two new minterms with the missing variable. Finally, you can loop through the finished minterms and "print" them to a result String.
Class declarations per request and for clarity (using public fields for brevity):
public class Atom {
public final char variable;
public final bool negated;
public Atom(char variable, bool negated) {
this.variable = variable;
this.negated = negated;
}
}
public class Minterm {
public final List<Atom> atoms = new ArrayList<Atom>();
}
In generateSumOfMinterms():
List<Minterm> expression = new ArrayList<Minterm>();
Minterm currentMinterm = new Minterm();
expression.add(currentMinterm);
Then, loop through the characters of termsOfTheFunction. Each time you see a letter, look at the next character to see if it is a ´, and add an Atom with that letter and with the correct negation. Each time you see a +, create a new Minterm and add it to expression, and keep going. Afterwards, you can start analyzing the minterms and expanding them.
Edit in response to your code: Looks like you're well on your way! The reason both atoms get added to the same minterm is that both m1 and m2 refer to the k'th minterm since you say m1 = minterms.get(k); and m2 = minterms.get(k);. get() does not copy or remove an element from a list; the element will still be inside the list. So for m2, you need to create a new minterm that has all of the atoms from the old one, plus the new atom.

Categories

Resources