From 3e900bb687f0ed8b34f6425e9ad7bdca7e1f6d39 Mon Sep 17 00:00:00 2001 From: Pavel Nikitin Date: Fri, 19 May 2017 14:39:44 +0200 Subject: [PATCH] optimize MathUtil.integerLogarithm --- .../java/jetbrains/exodus/util/MathUtil.java | 23 ++---------- .../java/jetbrains/exodus/util/MathTest.java | 35 +++++++++++++++++++ 2 files changed, 38 insertions(+), 20 deletions(-) create mode 100644 utils/src/test/java/jetbrains/exodus/util/MathTest.java diff --git a/utils/src/main/java/jetbrains/exodus/util/MathUtil.java b/utils/src/main/java/jetbrains/exodus/util/MathUtil.java index c65897c10..6fb563563 100644 --- a/utils/src/main/java/jetbrains/exodus/util/MathUtil.java +++ b/utils/src/main/java/jetbrains/exodus/util/MathUtil.java @@ -15,33 +15,16 @@ */ package jetbrains.exodus.util; -import java.util.Arrays; - public class MathUtil { - private static final int POWERS_OF_2[]; - - static { - POWERS_OF_2 = new int[31]; - int power = 1; - for (int i = 0; i < POWERS_OF_2.length; ++i) { - POWERS_OF_2[i] = power; - power <<= 1; - } - } - - private MathUtil() { - } - /** * @param i integer * @return discrete logarithm of specified integer base 2 */ public static int integerLogarithm(final int i) { - int result = Arrays.binarySearch(POWERS_OF_2, i); - if (result < 0) { - result = ~result; + if (i <= 0) { + return 0; } - return result; + return Integer.SIZE - Integer.numberOfLeadingZeros(i - 1); } } diff --git a/utils/src/test/java/jetbrains/exodus/util/MathTest.java b/utils/src/test/java/jetbrains/exodus/util/MathTest.java new file mode 100644 index 000000000..483881f28 --- /dev/null +++ b/utils/src/test/java/jetbrains/exodus/util/MathTest.java @@ -0,0 +1,35 @@ +/** + * Copyright 2010 - 2017 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package jetbrains.exodus.util; + +import org.junit.Assert; +import org.junit.Test; + +public class MathTest { + + @Test + public void testLog() { + int power = 1; + int expected = 0; + for (int i = 0; i < 10000; i++) { + Assert.assertEquals(expected, MathUtil.integerLogarithm(i)); + if (i == power) { + power <<= 1; + expected++; + } + } + } +}