Skip to content

Instantly share code, notes, and snippets.

@DarkGuardsman
Created April 13, 2018 07:47
Show Gist options
  • Save DarkGuardsman/5729a903df555672548ce9ce396819b4 to your computer and use it in GitHub Desktop.
Save DarkGuardsman/5729a903df555672548ce9ce396819b4 to your computer and use it in GitHub Desktop.
HashSet vs ArrayList #add(BlockPos) test to check performance
package com.builtbroken.jlib;
import com.builtbroken.jlib.lang.StringHelpers;
import net.minecraft.util.math.BlockPos;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.function.Consumer;
/**
* Test to check the time difference in using ArrayList vs HashSet for BlockPos
*
* Test checks time for #add(BlockPos) only
*
* @see <a href="https://github.com/BuiltBrokenModding/VoltzEngine/blob/development/license.md">License</a> for what you can and can't do with the code.
* Created by DarkCow on 4/13/2018.
*/
public class Main
{
public static void main(String[] args)
{
int size = 50;
int runs = 1000;
long total = 0L;
for (int i = 0; i < runs; i++)
{
List<BlockPos> list = new ArrayList();
//Track start time
long time = System.nanoTime();
//Generate data
generateData(size, b -> list.add(b));
//Track time taken
time = System.nanoTime() - time;
//Track total time for average
total += time;
//Debug
System.out.println(String.format("Size: %s completed: %s", list.size(), StringHelpers.formatNanoTime(time)));
}
long total2 = 0L;
for (int i = 0; i < runs; i++)
{
HashSet<BlockPos> list = new HashSet();
//Track start time
long time = System.nanoTime();
//Generate data
generateData(size, b -> list.add(b));
//Track time taken
time = System.nanoTime() - time;
//Track total time for average
total2 += time;
//Debug
System.out.println(String.format("Size: %s completed: %s", list.size(), StringHelpers.formatNanoTime(time)));
}
total /= runs;
total2 /= runs;
System.out.println(String.format("Time A: %s Time B: %s", StringHelpers.formatNanoTime(total), StringHelpers.formatNanoTime(total2)));
}
public static void generateData(int size, Consumer<BlockPos> list)
{
int y_min = Math.max(0, 128 - size);
int y_max = Math.min(255, 128 + size);
for (int x = -size; x <= size; x++)
{
for (int z = -size; z <= size; z++)
{
for (int y = y_min; y <= y_max; y++)
{
list.accept(new BlockPos(x, y, z));
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment