Categories
discuss

GC optimization: for vs foreach

I’ve been trying to optimize some of my code, and ive reached a strange conclusion regarding fors.

In my testcase ive created a new project with main activity. The activity initializes a List of 500 objects, runs an explicit GC and starts the thread. The thread loops the function doCalculations.

this.objects is a list of 500 MyObject, previous is MyObject, value is int. The function logics hold no logic, they are just there to do stuff. The difference is in the inner for.

function1

public void doCalculations()
{
    for(MyObject o : this.objects)
            for(int i=0; i<this.objects.size(); i++)
                if(this.objects.get(i) == o)
                    o.value = this.objects.get(i).value;
}

function 2

public void doCalculations()
{
    for(MyObject o : this.objects)
            for(MyObject o2 : this.objects)
                if(o2 == o)
                    o.value = o2.value;
}   

With function 2 GC is called every ~10 secs on my nexus s, freeing ~1.7MB.

With function 1 GC is never to be seen.

Why is that?

Answer

One creates an iterator, the other doesn’t.

Is the GC actually a bottleneck in your application? (It seems unlikely. Many devs, myself included, would consider the readability benefit to outweigh a few microseconds of GC.)

That said, your entire loop is a no-op anyway.

Categories
discuss

Unmarshalling errors in Android app with custom parcelable classes

For my Android application, I get several unmarshalling errors although I think I’ve done everything that is needed to properly save and load objects via Parcelables. Can you tell me what’s wrong with my code?

Error 1:

java.lang.RuntimeException: Unable to start activity ComponentInfo
Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@41279860: Unmarshalling unknown type code 6619241 at offset 1372
at android.os.Parcel.readValue(Parcel.java:1922)
at android.os.Parcel.readMapInternal(Parcel.java:2094)
at android.os.Bundle.unparcel(Bundle.java:223)
at android.os.Bundle.getParcelable(Bundle.java:1158)
at android.app.Activity.onCreate(Activity.java:860)
at my.app.package.PlayComputer.onCreate(PlayComputer.java:1012)
at android.app.Activity.performCreate(Activity.java:4465)

Line 1012 in MyActivity is the call to super.onCreate(savedInstanceState); in the Activity‘s onCreate().

protected void onSaveInstanceState(Bundle savedInstanceState) {
    if (myObject == null) {
        savedInstanceState.putParcelable("myObject", null);
    }
    else {
        savedInstanceState.putParcelable("myObject", myObject);
    }
    savedInstanceState.putInt(...);
    savedInstanceState.putString(...);
    savedInstanceState.putBoolean(...);
    super.onSaveInstanceState(savedInstanceState);
}

myObject is of class MyObject which has the following methods:

public void writeToParcel(Parcel out, int flags) {
    out.writeIntArray(...);
    out.writeInt(...);
    out.writeStringArray(...);
    out.writeString(...);
    out.writeParcelableArray(..., flags);
}

public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
    public MyObject createFromParcel(Parcel in) {
        try {
            if (in == null) {
                return null;
            }
            else {
                return new MyObject(in);
            }
        }
        catch (Exception e) {
            return null;
        }
    }
    public MyObject[] newArray(int size) {
        return new MyObject[size];
    }
};

private MyObject(Parcel in) {
    in.readIntArray(...);
    ... = in.readInt();
    in.readStringArray(...);
    ... = in.readString();
    ... = (OtherObject[]) in.readParcelableArray(OtherObject.class.getClassLoader());
}

Error 2:

java.lang.RuntimeException: Unable to start activity ComponentInfo
Caused by: android.os.BadParcelableException: ClassNotFoundException when unmarshalling:
at android.os.Parcel.readParcelable(Parcel.java:1971)
at android.os.Parcel.readValue(Parcel.java:1859)
at android.os.Parcel.readMapInternal(Parcel.java:2099)
at android.os.Bundle.unparcel(Bundle.java:223)
at android.os.Bundle.getParcelable(Bundle.java:1158)
at android.app.Activity.onCreate(Activity.java:905)
at my.app.package.PlayComputer.onCreate(SourceFile:1012)

Same files and classes.

Error 3:

java.lang.RuntimeException: Unable to start activity ComponentInfo
Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@4051aff8: Unmarshalling unknown type code 7340149 at offset 1276
at android.os.Parcel.readValue(Parcel.java:1913)
at android.os.Parcel.readMapInternal(Parcel.java:2083)
at android.os.Bundle.unparcel(Bundle.java:208)
at android.os.Bundle.getParcelable(Bundle.java:1100)
at my.app.package.PlayComputer.onCreate(SourceFile:1111)

This time, the causing line (1111) is the following one:

myObject = (MyObject) savedInstanceState.getParcelable("myObject");

Answer

Android has two different classloaders: the framework classloader (which knows how to load Android classes) and the APK classloader (which knows how to load your code). The APK classloader has the framework classloader set as its parent, meaning it can also load Android classes.

Error #2 is likely caused by the Bundle using the framework classloader so it doesn’t know of your classes. I think this can happen when Android needs to persist your Bundle and later restore it (for example when running out of memory in the background). You can fix this by setting the APK classloader on the bundle:

savedInstanceState.setClassLoader(getClass().getClassLoader());

Error #1 and #3 are more mysterious, are you perhaps writing null values in writeToParcel()? Android doesn’t like that very much I’m afraid.

Categories
discuss

Why does Java’s RoundingMode HALF_UP round -2.5 to -3?

RoundingMode allows the programmer to specify in what manner floating point numbers are to be rounded. This is great and all, but there is this one thing about it I found peculiar. Maybe I just misunderstood something fundamental at school.

But this rounding mode is described as the one I was taught at school, “Always round to the nearest number, and when dead in the center, always round up.”, but why does it round -2.5 to -3?

I conclude as much that it rounds up in terms of absolute values, but -2 is, to me, certainly “up” from -2.5.

Answer

RoundingMode.UP is the rounding mode for “away from zero.” RoundingMode.FLOOR is towards negative infinity, and CEILING is towards positive infinity. HALF_UP is consistent with UP when the fractional part is exactly 0.5.

They had to choose some term to mean “away from zero.”

Categories
discuss

How to fix side bar and header using CSS for JS & jQuery Scroller

I have this layout and I want to make the left sidebar, right sidebar and the header fixed.

enter image description here

This is my css :

    #container {
        padding-left: 200px;      /* LC fullwidth */
        padding-right: 190px;     /* RC fullwidth + CC padding */
    }

    #container .column {
        position: relative;
        float: left;
    }

    #center {
        padding: 10px 20px;       /* CC padding */
        width: 100%;
        overflow-x:hidden;
    }

    #left {
        width: 180px;             /* LC width */
        padding: 0 10px;          /* LC padding */
        right: 240px;             /* LC fullwidth + CC padding */
        margin-left: -100%;
    }

    #right {
        width: 130px;             /* RC width */
        padding: 0 10px;          /* RC padding */
        margin-right: -100%;
    }

    #footer {
        clear: both;
    }

& the code is here

After this step, I want to add nanScrollerJS to the right side bar.

I’m not familiar with CSS

Answer

Is this what you were trying to do?

Fiddle

I’ve erased almost all of your code and replaced it with new code.

#fixed

position: fixed;
top: 0;
left: 0;
width: 100%;

#center

margin-top: 32px; /* Header height */
padding: 10px 20px; /* CC padding */
box-sizing: border-box;
border-left: 200px solid black; /* LC width including padding */
border-right: 150px solid black; /* RC width including padding */

#left

width: 180px; /* LC width */
padding: 0 10px; /* LC padding */
float: left;

#right

width: 130px; /* RC width */
padding: 0 10px; /* RC padding */
float: right;

#footer

position: relative;
z-index: 1;
Categories
discuss

Error using both lookahead and look behind regex

I am having a problem using the following regex. It works fine in regexr and rubular but it gives me an error when running it on node.js. I am fairly new to using regex and i’m not sure what i’m doing wrong. It will work if I knock off the (?<= ) so I presume that is the problem.

I’m trying to match ‘is’ with a leading and trailing space using /(?<= )is(?= )|==/g

Example with test words:
http://regexr.com?33781

Node error output

 temp = temp.replace(/(?<= )is(?= )|==/g, '===');
^
SyntaxError: Invalid regular expression: /(?<= )is(?= )|==/: Invalid group
at new RegExp (unknown source)

Answer

JavaScript regex does not support lookbehind at all.

Sources:

However, you can fake it in some cases.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..