performance

This commit is contained in:
Arndt Brenschede 2016-09-09 19:42:00 +02:00
parent 62d089ebb5
commit 9d00b0181e
14 changed files with 194 additions and 105 deletions

View file

@ -99,7 +99,12 @@ public final class TagValueCoder
node.child2 = decodeTree( bc, buffer, validator ); node.child2 = decodeTree( bc, buffer, validator );
return node; return node;
} }
int startpos = bc.getReadingBitPosition();
BitCoderContext ctx = new BitCoderContext( buffer );
int inum = 0;
int lastEncodedInum = 0;
boolean hasdata = false; boolean hasdata = false;
for ( ;; ) for ( ;; )
{ {
@ -110,22 +115,36 @@ public final class TagValueCoder
{ {
return null; return null;
} }
hasdata = true;
} }
if ( delta == 0 ) if ( delta == 0 )
{ {
ctx.encodeVarBits( 0 );
break; break;
} }
bc.decodeVarBits(); inum += delta;
int data = bc.decodeVarBits();
if ( validator == null || validator.isLookupIdxUsed( inum ) )
{
hasdata = true;
ctx.encodeVarBits( inum - lastEncodedInum );
ctx.encodeVarBits( data );
lastEncodedInum = inum;
}
} }
int endpos = bc.getReadingBitPosition();
int bitcount = endpos - startpos; byte[] res;
int bytecount = ( bitcount + 7 ) >> 3; int len = ctx.getEncodedLength();
if ( validator == null )
bc.setReadingBitPosition( startpos ); {
byte[] res = new byte[bytecount]; res = new byte[len];
bc.copyBitsTo( res, bitcount ); System.arraycopy( buffer, 0, res, 0, len );
}
else
{
res = validator.unify( buffer, 0, len );
}
int accessType = validator == null ? 2 : validator.accessType( res ); int accessType = validator == null ? 2 : validator.accessType( res );
if ( accessType > 0 ) if ( accessType > 0 )

View file

@ -8,4 +8,9 @@ public interface TagValueValidator
* @return 0 = nothing, 1=no matching, 2=normal * @return 0 = nothing, 1=no matching, 2=normal
*/ */
public int accessType( byte[] tagValueSet ); public int accessType( byte[] tagValueSet );
public byte[] unify( byte[] tagValueSet, int offset, int len );
public boolean isLookupIdxUsed( int idx );
} }

View file

@ -17,6 +17,8 @@ import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -327,14 +329,28 @@ public final class OsmTrack
public void writeGpx( String filename ) throws Exception public void writeGpx( String filename ) throws Exception
{ {
BufferedWriter bw = new BufferedWriter( new FileWriter( filename ) ); BufferedWriter bw = new BufferedWriter( new FileWriter( filename ) );
formatAsGpx( bw );
bw.write( formatAsGpx() );
bw.close(); bw.close();
} }
public String formatAsGpx() public String formatAsGpx()
{ {
StringBuilder sb = new StringBuilder( 8192 ); try
{
StringWriter sw = new StringWriter( 8192 );
BufferedWriter bw = new BufferedWriter( sw );
formatAsGpx( bw );
bw.close();
return sw.toString();
}
catch( Exception e )
{
throw new RuntimeException( e );
}
}
public String formatAsGpx( BufferedWriter sb ) throws IOException
{
int turnInstructionMode = voiceHints != null ? voiceHints.turnInstructionMode : 0; int turnInstructionMode = voiceHints != null ? voiceHints.turnInstructionMode : 0;
sb.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ); sb.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
@ -385,8 +401,8 @@ public final class OsmTrack
sb.append(" <rtept lat=\"").append( formatILat( hint.ilat ) ).append( "\" lon=\"" ) sb.append(" <rtept lat=\"").append( formatILat( hint.ilat ) ).append( "\" lon=\"" )
.append( formatILon( hint.ilon ) ).append( "\">\n" ) .append( formatILon( hint.ilon ) ).append( "\">\n" )
.append ( " <desc>" ).append( hint.getMessageString() ).append( "</desc>\n <extensions>\n <turn>" ) .append ( " <desc>" ).append( hint.getMessageString() ).append( "</desc>\n <extensions>\n <turn>" )
.append( hint.getCommandString() ).append("</turn>\n <turn-angle>").append( hint.angle ) .append( hint.getCommandString() ).append("</turn>\n <turn-angle>").append( "" + hint.angle )
.append("</turn-angle>\n <offset>").append( hint.indexInTrack ).append("</offset>\n </extensions>\n </rtept>\n"); .append("</turn-angle>\n <offset>").append( "" + hint.indexInTrack ).append("</offset>\n </extensions>\n </rtept>\n");
} }
sb.append("</rte>\n"); sb.append("</rte>\n");
} }
@ -399,8 +415,8 @@ public final class OsmTrack
.append( formatILat( hint.ilat ) ).append( "\">" ) .append( formatILat( hint.ilat ) ).append( "\">" )
.append( hint.selev == Short.MIN_VALUE ? "" : "<ele>" + (hint.selev / 4.) + "</ele>" ) .append( hint.selev == Short.MIN_VALUE ? "" : "<ele>" + (hint.selev / 4.) + "</ele>" )
.append( "<name>" ).append( hint.getMessageString() ).append( "</name>" ) .append( "<name>" ).append( hint.getMessageString() ).append( "</name>" )
.append( "<extensions><locus:rteDistance>" ).append( hint.distanceToNext ).append( "</locus:rteDistance>" ) .append( "<extensions><locus:rteDistance>" ).append( "" + hint.distanceToNext ).append( "</locus:rteDistance>" )
.append( "<locus:rtePointAction>" ).append( hint.getLocusAction() ).append( "</locus:rtePointAction></extensions>" ) .append( "<locus:rtePointAction>" ).append( "" + hint.getLocusAction() ).append( "</locus:rtePointAction></extensions>" )
.append( "</wpt>\n" ); .append( "</wpt>\n" );
} }
} }
@ -425,7 +441,7 @@ public final class OsmTrack
if ( turnInstructionMode == 2 ) if ( turnInstructionMode == 2 )
{ {
sb.append( " <extensions><locus:rteComputeType>" ).append( voiceHints.getLocusRouteType() ).append( "</locus:rteComputeType></extensions>\n" ); sb.append( " <extensions><locus:rteComputeType>" ).append( "" + voiceHints.getLocusRouteType() ).append( "</locus:rteComputeType></extensions>\n" );
sb.append( " <extensions><locus:rteSimpleRoundabouts>1</locus:rteSimpleRoundabouts></extensions>\n" ); sb.append( " <extensions><locus:rteSimpleRoundabouts>1</locus:rteSimpleRoundabouts></extensions>\n" );
} }

View file

@ -63,8 +63,8 @@ public final class ProfileCache
BExpressionMetaData meta = new BExpressionMetaData(); BExpressionMetaData meta = new BExpressionMetaData();
BExpressionContextGlobal expctxGlobal = new BExpressionContextGlobal( meta ); BExpressionContextGlobal expctxGlobal = new BExpressionContextGlobal( meta );
rc.expctxWay = new BExpressionContextWay( rc.serversizing ? 131072 : 32768, meta ); rc.expctxWay = new BExpressionContextWay( rc.memoryclass * 512, meta );
rc.expctxNode = new BExpressionContextNode( rc.serversizing ? 4096 : 1024, meta ); rc.expctxNode = new BExpressionContextNode( rc.memoryclass * 128, meta );
meta.readMetaData( new File( profileDir, "lookups.dat" ) ); meta.readMetaData( new File( profileDir, "lookups.dat" ) );

View file

@ -41,7 +41,7 @@ public final class RoutingContext
public BExpressionContextWay expctxWay; public BExpressionContextWay expctxWay;
public BExpressionContextNode expctxNode; public BExpressionContextNode expctxNode;
public boolean serversizing = false; public int memoryclass = 64;
public int downhillcostdiv; public int downhillcostdiv;
public int downhillcutoff; public int downhillcutoff;

View file

@ -173,6 +173,7 @@ public class RoutingEngine extends Thread
{ {
continue; continue;
} }
oldTrack = null;
track.writeGpx( filename ); track.writeGpx( filename );
foundTrack = track; foundTrack = track;
alternativeIndex = i; alternativeIndex = i;
@ -573,7 +574,10 @@ public class RoutingEngine extends Thread
logInfo( "NodesCache status before reset=" + nodesCache.formatStatus() ); logInfo( "NodesCache status before reset=" + nodesCache.formatStatus() );
} }
nodesMap = new OsmNodesMap(); nodesMap = new OsmNodesMap();
nodesCache = new NodesCache(segmentDir, nodesMap, routingContext.expctxWay, routingContext.forceSecondaryData, nodesCache );
long maxmem = routingContext.memoryclass * 131072L; // 1/4 of total
nodesCache = new NodesCache(segmentDir, nodesMap, routingContext.expctxWay, routingContext.forceSecondaryData, maxmem, nodesCache );
} }
private OsmNode getStartNode( long startId ) private OsmNode getStartNode( long startId )
@ -699,6 +703,20 @@ public class RoutingEngine extends Thread
} }
private OsmTrack findTrack( String operationName, MatchedWaypoint startWp, MatchedWaypoint endWp, OsmTrack costCuttingTrack, OsmTrack refTrack, boolean fastPartialRecalc ) private OsmTrack findTrack( String operationName, MatchedWaypoint startWp, MatchedWaypoint endWp, OsmTrack costCuttingTrack, OsmTrack refTrack, boolean fastPartialRecalc )
{
try
{
resetCache();
return _findTrack( operationName, startWp, endWp, costCuttingTrack, refTrack, fastPartialRecalc );
}
finally
{
nodesCache.cleanNonVirgin();
}
}
private OsmTrack _findTrack( String operationName, MatchedWaypoint startWp, MatchedWaypoint endWp, OsmTrack costCuttingTrack, OsmTrack refTrack, boolean fastPartialRecalc )
{ {
boolean verbose = guideTrack != null; boolean verbose = guideTrack != null;
@ -711,7 +729,6 @@ public class RoutingEngine extends Thread
matchPath = null; matchPath = null;
int nodesVisited = 0; int nodesVisited = 0;
resetCache();
long endNodeId1 = endWp == null ? -1L : endWp.node1.getIdFromPos(); long endNodeId1 = endWp == null ? -1L : endWp.node1.getIdFromPos();
long endNodeId2 = endWp == null ? -1L : endWp.node2.getIdFromPos(); long endNodeId2 = endWp == null ? -1L : endWp.node2.getIdFromPos();
long startNodeId1 = startWp.node1.getIdFromPos(); long startNodeId1 = startWp.node1.getIdFromPos();

View file

@ -160,6 +160,7 @@ final class BExpression
{ {
throw new IllegalArgumentException( "unknown lookup name: " + name ); throw new IllegalArgumentException( "unknown lookup name: " + name );
} }
ctx.markLookupIdxUsed( exp.lookupNameIdx );
StringTokenizer tk = new StringTokenizer( values, "|" ); StringTokenizer tk = new StringTokenizer( values, "|" );
int nt = tk.countTokens(); int nt = tk.countTokens();
int nt2 = nt == 0 ? 1 : nt; int nt2 = nt == 0 ? 1 : nt;

View file

@ -37,6 +37,7 @@ public abstract class BExpressionContext implements IByteArrayUnifier
private ArrayList<BExpressionLookupValue[]> lookupValues = new ArrayList<BExpressionLookupValue[]>(); private ArrayList<BExpressionLookupValue[]> lookupValues = new ArrayList<BExpressionLookupValue[]>();
private ArrayList<String> lookupNames = new ArrayList<String>(); private ArrayList<String> lookupNames = new ArrayList<String>();
private ArrayList<int[]> lookupHistograms = new ArrayList<int[]>(); private ArrayList<int[]> lookupHistograms = new ArrayList<int[]>();
private boolean[] lookupIdxUsed;
private boolean lookupDataFrozen = false; private boolean lookupDataFrozen = false;
@ -255,6 +256,8 @@ public abstract class BExpressionContext implements IByteArrayUnifier
// post-process metadata: // post-process metadata:
lookupDataFrozen = true; lookupDataFrozen = true;
lookupIdxUsed = new boolean[lookupValues.size()];
} }
public final void evaluate( int[] lookupData2 ) public final void evaluate( int[] lookupData2 )
@ -281,6 +284,8 @@ public abstract class BExpressionContext implements IByteArrayUnifier
return "requests=" + requests + " requests2=" + requests2 + " cachemisses=" + cachemisses; return "requests=" + requests + " requests2=" + requests2 + " cachemisses=" + cachemisses;
} }
private CacheNode lastCacheNode = new CacheNode();
// @Override // @Override
public final byte[] unify( byte[] ab, int offset, int len ) public final byte[] unify( byte[] ab, int offset, int len )
{ {
@ -303,6 +308,7 @@ public abstract class BExpressionContext implements IByteArrayUnifier
} }
if ( cn != null ) if ( cn != null )
{ {
lastCacheNode = cn;
return cn.ab; return cn.ab;
} }
} }
@ -318,10 +324,18 @@ public abstract class BExpressionContext implements IByteArrayUnifier
requests++; requests++;
lookupDataValid = false; // this is an assertion for a nasty pifall lookupDataValid = false; // this is an assertion for a nasty pifall
CacheNode cn;
if ( lastCacheNode.ab == ab )
{
cn = lastCacheNode;
}
else
{
probeCacheNode.ab = ab; probeCacheNode.ab = ab;
probeCacheNode.crc = Crc32.crc( ab, 0, ab.length ); probeCacheNode.crc = Crc32.crc( ab, 0, ab.length );
cn = (CacheNode)cache.get( probeCacheNode );
}
CacheNode cn = (CacheNode)cache.get( probeCacheNode );
if ( cn == null ) if ( cn == null )
{ {
cachemisses++; cachemisses++;
@ -746,6 +760,16 @@ public abstract class BExpressionContext implements IByteArrayUnifier
return num == null ? -1 : num.intValue(); return num == null ? -1 : num.intValue();
} }
public final void markLookupIdxUsed( int idx )
{
lookupIdxUsed[ idx ] = true;
}
public final boolean isLookupIdxUsed( int idx )
{
return idx < lookupIdxUsed.length ? lookupIdxUsed[idx] : false;
}
int getLookupValueIdx( int nameIdx, String value ) int getLookupValueIdx( int nameIdx, String value )
{ {
BExpressionLookupValue[] values = lookupValues.get( nameIdx ); BExpressionLookupValue[] values = lookupValues.get( nameIdx );

View file

@ -32,7 +32,6 @@ public final class NodesCache
private DataBuffers dataBuffers; private DataBuffers dataBuffers;
private OsmFile[][] fileRows; private OsmFile[][] fileRows;
private ArrayList<MicroCache> segmentList = new ArrayList<MicroCache>();
public WaypointMatcher waypointMatcher; public WaypointMatcher waypointMatcher;
@ -40,14 +39,17 @@ public final class NodesCache
public String first_file_access_name; public String first_file_access_name;
private long cacheSum = 0; private long cacheSum = 0;
private long maxmem;
private boolean garbageCollectionEnabled = false; private boolean garbageCollectionEnabled = false;
private boolean ghostCleaningDone = false;
public String formatStatus() public String formatStatus()
{ {
return "collecting=" + garbageCollectionEnabled + " cacheSum=" + cacheSum; return "collecting=" + garbageCollectionEnabled + " noGhosts=" + ghostCleaningDone + " cacheSum=" + cacheSum;
} }
public NodesCache( String segmentDir, OsmNodesMap nodesMap, BExpressionContextWay ctxWay, boolean forceSecondaryData, NodesCache oldCache ) public NodesCache( String segmentDir, OsmNodesMap nodesMap, BExpressionContextWay ctxWay, boolean forceSecondaryData, long maxmem, NodesCache oldCache )
{ {
this.segmentDir = new File( segmentDir ); this.segmentDir = new File( segmentDir );
this.nodesMap = nodesMap; this.nodesMap = nodesMap;
@ -55,6 +57,7 @@ public final class NodesCache
this.lookupVersion = ctxWay.meta.lookupVersion; this.lookupVersion = ctxWay.meta.lookupVersion;
this.lookupMinorVersion = ctxWay.meta.lookupMinorVersion; this.lookupMinorVersion = ctxWay.meta.lookupMinorVersion;
this.forceSecondaryData = forceSecondaryData; this.forceSecondaryData = forceSecondaryData;
this.maxmem = maxmem;
first_file_access_failed = false; first_file_access_failed = false;
first_file_access_name = null; first_file_access_name = null;
@ -89,11 +92,24 @@ public final class NodesCache
} }
} }
public void cleanNonVirgin()
{
for ( OsmFile[] fileRow : fileRows )
{
if ( fileRow == null )
continue;
for ( OsmFile osmf : fileRow )
{
osmf.cleanNonVirgin();
}
}
}
// if the cache sum exceeded a threshold, // if the cache sum exceeded a threshold,
// clean all ghosts and enable garbage collection // clean all ghosts and enable garbage collection
private void checkEnableCacheCleaning() private void checkEnableCacheCleaning()
{ {
if ( cacheSum < 3000000 || garbageCollectionEnabled ) if ( cacheSum < maxmem || ghostCleaningDone )
return; return;
for ( int i = 0; i < fileRows.length; i++ ) for ( int i = 0; i < fileRows.length; i++ )
@ -103,12 +119,19 @@ public final class NodesCache
continue; continue;
int nghosts = 0; int nghosts = 0;
for ( OsmFile osmf : fileRow ) for ( OsmFile osmf : fileRow )
{
if ( garbageCollectionEnabled )
{ {
if ( osmf.ghost ) if ( osmf.ghost )
{
nghosts++; nghosts++;
}
}
else else
{
osmf.cleanAll(); osmf.cleanAll();
} }
}
if ( nghosts == 0 ) if ( nghosts == 0 )
continue; continue;
int j = 0; int j = 0;
@ -121,8 +144,16 @@ public final class NodesCache
} }
fileRows[i] = frow; fileRows[i] = frow;
} }
if ( garbageCollectionEnabled )
{
ghostCleaningDone = true;
}
else
{
garbageCollectionEnabled = true; garbageCollectionEnabled = true;
} }
}
public int loadSegmentFor( int ilon, int ilat ) public int loadSegmentFor( int ilon, int ilat )
{ {
@ -173,18 +204,10 @@ public final class NodesCache
segment = osmf.createMicroCache( ilon, ilat, dataBuffers, expCtxWay, waypointMatcher ); segment = osmf.createMicroCache( ilon, ilat, dataBuffers, expCtxWay, waypointMatcher );
cacheSum += segment.getDataSize(); cacheSum += segment.getDataSize();
if ( segment.getSize() > 0 )
{
segmentList.add( segment );
}
} }
else if ( segment.ghost ) else if ( segment.ghost )
{ {
segment.unGhost(); segment.unGhost();
if ( segment.getSize() > 0 )
{
segmentList.add( segment );
}
} }
return segment; return segment;
} }
@ -217,7 +240,7 @@ public final class NodesCache
if ( garbageCollectionEnabled ) // garbage collection if ( garbageCollectionEnabled ) // garbage collection
{ {
segment.collect( segment.getSize() >> 1 ); segment.collect( segment.getSize() >> 2 ); // threshold = 1/4 of size is deleted
} }
return !node.isHollow(); return !node.isHollow();
@ -276,27 +299,6 @@ public final class NodesCache
return osmf; return osmf;
} }
public List<OsmNode> getAllNodes()
{
List<OsmNode> all = new ArrayList<OsmNode>();
for ( MicroCache segment : segmentList )
{
ArrayList<OsmNode> positions = new ArrayList<OsmNode>();
int size = segment.getSize();
for ( int i = 0; i < size; i++ )
{
long id = segment.getIdForIndex( i );
OsmNode n = new OsmNode( id );
n.setHollow();
nodesMap.put( n );
positions.add( n );
}
all.addAll( positions );
}
return all;
}
public void close() public void close()
{ {
for ( PhysicalFile f : fileCache.values() ) for ( PhysicalFile f : fileCache.values() )

View file

@ -201,4 +201,18 @@ final class OsmFile
} }
} }
void cleanNonVirgin()
{
int nc = microCaches == null ? 0 : microCaches.length;
for ( int i = 0; i < nc; i++ )
{
MicroCache mc = microCaches[i];
if ( mc == null )
continue;
if ( !mc.virgin )
{
microCaches[i] = null;
}
}
}
} }

View file

@ -7,6 +7,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import android.app.Activity; import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.Dialog; import android.app.Dialog;
import android.content.Context; import android.content.Context;
@ -57,8 +58,11 @@ public class BRouterActivity extends Activity implements OnInitListener
// Create a bright wake lock // Create a bright wake lock
mWakeLock = mPowerManager.newWakeLock( PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass().getName() ); mWakeLock = mPowerManager.newWakeLock( PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass().getName() );
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
// instantiate our simulation view and set it as the activity's content // instantiate our simulation view and set it as the activity's content
mBRouterView = new BRouterView( this ); mBRouterView = new BRouterView( this, memoryClass );
mBRouterView.init(); mBRouterView.init();
setContentView( mBRouterView ); setContentView( mBRouterView );
} }

View file

@ -75,14 +75,17 @@ public class BRouterView extends View
private int[] imgPixels; private int[] imgPixels;
private int memoryClass;
public void stopRouting() public void stopRouting()
{ {
if ( cr != null ) cr.terminate(); if ( cr != null ) cr.terminate();
} }
public BRouterView( Context context ) public BRouterView( Context context, int memoryClass )
{ {
super( context ); super( context );
this.memoryClass = memoryClass;
} }
public void init() public void init()
@ -221,10 +224,14 @@ public class BRouterView extends View
} }
catch( Exception e ) catch( Exception e )
{ {
tracksDir = basedir + "/brouter"; tracksDir = null;
} }
} }
} }
if ( tracksDir == null )
{
tracksDir = basedir + "/brouter"; // fallback
}
String[] fileNames = new File( profileDir ).list(); String[] fileNames = new File( profileDir ).list();
ArrayList<String> profiles = new ArrayList<String>(); ArrayList<String> profiles = new ArrayList<String>();
@ -515,6 +522,17 @@ public class BRouterView extends View
rc.prepareNogoPoints( nogoList ); rc.prepareNogoPoints( nogoList );
rc.nogopoints = nogoList; rc.nogopoints = nogoList;
rc.memoryclass = memoryClass;
if ( memoryClass < 16 )
{
rc.memoryclass = 16;
}
else if ( memoryClass > 256 )
{
rc.memoryclass = 256;
}
// for profile remote, use ref-track logic same as service interface // for profile remote, use ref-track logic same as service interface
rc.rawTrackPath = rawTrackPath; rc.rawTrackPath = rawTrackPath;
@ -748,7 +766,7 @@ public class BRouterView extends View
} }
else else
{ {
String result = "version = BRouter-1.4.4\n" + "distance = " + cr.getDistance() / 1000. + " km\n" + "filtered ascend = " + cr.getAscend() String result = "version = BRouter-1.4.4\n" + "memory-class = " + memoryClass + "\ndistance = " + cr.getDistance() / 1000. + " km\n" + "filtered ascend = " + cr.getAscend()
+ " m\n" + "plain ascend = " + cr.getPlainAscend(); + " m\n" + "plain ascend = " + cr.getPlainAscend();
rawTrack = cr.getFoundRawTrack(); rawTrack = cr.getFoundRawTrack();

View file

@ -41,7 +41,7 @@ public class ServerHandler extends RequestHandler {
public RoutingContext readRoutingContext() public RoutingContext readRoutingContext()
{ {
rc = new RoutingContext(); rc = new RoutingContext();
rc.serversizing = true; rc.memoryclass = 128;
String profile = params.get( "profile" ); String profile = params.get( "profile" );
// when custom profile replace prefix with directory path // when custom profile replace prefix with directory path

View file

@ -34,35 +34,6 @@ public final class SortedHeap<V>
/** /**
* @return the lowest key value, or null if none * @return the lowest key value, or null if none
*/ */
public V popLowestKeyValue2()
{
int minId = 0;
int minIdx = -1;
for ( int i = 0;; i++ )
{
int[] ali = al[i];
if ( ali == null )
break;
int lpi = lp[i];
if ( lpi < 4 << i )
{
int currentId = ali[lpi];
if ( minIdx < 0 || currentId < minId )
{
minIdx = i;
minId = currentId;
}
}
}
if ( minIdx == -1 )
return null;
size--;
return dropLowest( minIdx );
}
public V popLowestKeyValue() public V popLowestKeyValue()
{ {
int idx = firstNonEmpty; int idx = firstNonEmpty;
@ -286,24 +257,22 @@ public final class SortedHeap<V>
{ {
int div = size / 1000 + 1; int div = size / 1000 + 1;
ArrayList<V> res = new ArrayList<V>( size / div ); ArrayList<V> res = new ArrayList<V>( size / div + 1 );
int cnt = 0; int lpi = 0;
for ( int i = 1;; i++ ) for ( int i = 1;; i++ )
{ {
int[] ali = al[i]; int[] ali = al[i];
if ( ali == null ) if ( ali == null )
break; break;
int lpi = lp[i]; lpi += lp[i];
Object[] vlai = vla[i]; Object[] vlai = vla[i];
int n = 4 << i; int n = 4 << i;
while (lpi < n) while (lpi < n)
{
if ( ( ++cnt ) % div == 0 )
{ {
res.add( (V) vla[i][lpi] ); res.add( (V) vla[i][lpi] );
lpi += div;
} }
lpi++; lpi -= n;
}
} }
return res; return res;
} }