Skip to content

Conversation

@lanicc
Copy link
Contributor

@lanicc lanicc commented Jan 14, 2021

Using List costs less memory and computing than HashSet.

@maoling
Copy link
Member

maoling commented Jan 22, 2021

@lanicc

Using List costs less memory and computing than HashSet.

Could you please give us more explanations for this? Any benchmark report?

@lanicc
Copy link
Contributor Author

lanicc commented Jan 27, 2021

simple test:

`public static void main(String[] args) {
int numObj = 1;

    Set<Object> set = new HashSet<>();
    for (int i = 0; i < numObj; i++) {
        set.add(new Object());
    }
    System.out.println("Size of HashSet: " + GraphLayout.parseInstance(set).totalSize());
    List<Object> list = new ArrayList<>();
    for (int i = 0; i < numObj; i++) {
        list.add(new Object());
    }
    System.out.println("Size of ArrayList: " + GraphLayout.parseInstance(list).totalSize());


    long start, end;

    Iterator<Object> setIterator = set.iterator();
    start = System.nanoTime();
    while (setIterator.hasNext()) {
        setIterator.next();
    }
    end = System.nanoTime();
    System.out.println("HashSet iterator cost: " + (end - start));

    Iterator<Object> listIterator = list.iterator();
    start = System.nanoTime();
    while (listIterator.hasNext()) {
        listIterator.next();
    }
    end = System.nanoTime();
    System.out.println("ArrayList iterator cost: " + (end - start));
}`

result:

Size of HashSet: 256
Size of ArrayList: 112
HashSet iterator cost: 20474
ArrayList iterator cost: 460

@lanicc
Copy link
Contributor Author

lanicc commented Jan 29, 2021

@maoling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants