Last active
July 10, 2019 08:26
-
-
Save ignasi35/7f7f6deddce522f26ec560d93308f83d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example | |
// Based on https://gist.github.com/412b/b383f0864c9dd4378ce22d616c694d64 which is part of https://github.com/akka/akka/pull/27309 | |
import java.security.MessageDigest | |
import java.util.Base64 | |
import java.util.concurrent.TimeUnit | |
import org.openjdk.jmh.annotations.{ | |
OutputTimeUnit, | |
Param, | |
Warmup, | |
Mode, | |
Benchmark, | |
Measurement, | |
State, | |
BenchmarkMode, | |
Fork, | |
Scope => JmhScope | |
} | |
@Fork(2) | |
@State(JmhScope.Benchmark) | |
@BenchmarkMode(Array(Mode.Throughput)) | |
@Warmup(iterations = 5) | |
@Measurement(iterations = 10) | |
@OutputTimeUnit(TimeUnit.MILLISECONDS) | |
class NodeHash { | |
// Use already digested inputs so benchmark only measures | |
// the change in the algorithm | |
// @Param(Array("j", "m", "h")) | |
@Param( | |
Array( | |
"NjsSLFKPVN9KBEa2urBVFQ==", // Base64(MD5("j")) see `build()` below | |
"b49XcVCQ2iYyRTmI2aFQGw==", // Base64(MD5("m")) | |
"JRDDkBHFvnBBgkI+OmlekQ==" // Base64(MD5("h")) | |
) | |
) | |
var value = "" | |
// val encoder = Base64.getEncoder | |
//// Given a name, produce it's MD5 in Base64 | |
// def build(name:String): String ={ | |
// val digester = MessageDigest.getInstance("MD5") | |
// digester.update(name.getBytes("UTF-8")) | |
// val digest = digester.digest | |
// encoder.encodeToString(digest) | |
// } | |
def hashCurrent(in: Array[Byte]): String = { | |
in.map { h => | |
"%02x".format(0xFF & h) | |
}.mkString | |
} | |
def hashProposed(in: Array[Byte]): String = { | |
val digest = in | |
val ch = new Array[Char](digest.length * 2) | |
var i = 0 | |
while (i < digest.length) { | |
val h = digest(i) | |
ch(i * 2) = Character.forDigit((h >> 4) & 0xF, 16) | |
ch(i * 2 + 1) = Character.forDigit(h & 0xF, 16) | |
i += 1 | |
} | |
String.valueOf(ch) | |
} | |
val decoder = Base64.getDecoder | |
@Benchmark | |
def proposed: String = hashProposed(decoder.decode(value)) | |
@Benchmark | |
def current: String = hashCurrent(decoder.decode(value)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment