8

我正在尝试使用 Unsafe 来迭代内存,而不是迭代 byte[] 中的值。使用 unsafe 分配内存块。内存足以容纳 65536 个字节的值。

我正在尝试这个:

char aChar = some character

if ((byte) 0 == (unsafe.getByte(base_address + aChar) & mask)){
 // do something
}

代替:

char aChar = some character

if ((byte) 0 == ( lookup[aChar] & mask )){
 // do something
}

认为Unsafe 可以比使用常规数组访问更快地访问内存,并为每个索引执行索引检查......

jvm 会有一个特殊的操作(不安全)以某种方式使常规数组访问和迭代更快,这只是一厢情愿。在我看来,jvm 在正常的 byte[] 迭代中运行良好,并且使用正常的、纯粹的、vanilla java 代码尽可能快地完成它们。

@millimoose 击中了众所周知的“头上钉子”

“不安全可能对很多事情都有用,但这种级别的微优化不是其中之一。——millimoose”

在非常严格的有限情况下,使用 Unsafe 会更快:

  • (仅限 64 位 jvm)对于每个测试只执行一次65535 字节 [] 查找更快。在这种情况下,64 位 jvm 上的 UnsafeLookup_8B 速度提高了 24%。如果测试重复进行,每次测试都进行两次,那么现在正常方法比不安全方法快 30%。在冷 jvm 上的纯解释模式下,Unsafe 到目前为止更快 --- 但只是第一次并且仅适用于小数组大小。在 32 位标准 Oracle JVM 7.x 上,正常比使用 unsafe 快三倍。

使用 Unsafe(在我的测试中)比较慢:

  • 在 Oracle java 64 位和 32 位虚拟机上速度较慢
  • 较慢的操作系统和机器架构(32 位和 64 位)
  • 即使server调用了 jvm 选项也更慢

  • Unsafe 比 9% 或更多慢(1_GB 数组和 UnsafeLookup_8B(fastest one) 在下面的 32 位 jvm 代码中(64 位甚至更慢??))

  • Unsafe 在 64 位 jvm 上低于 234% 或更多( 1_MB 数组和 UnsafeLookup_1B (最快)在下面的代码中。

这有什么原因吗?**

当我运行下面发布的代码 YellowB 时(检查 1GB 字节 []),正常情况下也是最快的:

C:\Users\wilf>java -Xms1600m -Xprof -jar "S:\wilf\testing\dist\testing.jar"
initialize data...
initialize data done!

use normalLookup()...
Not found '0'
time : 1967737 us.

use unsafeLookup_1B()...
Not found '0'
time : 2923367 us.

use unsafeLookup_8B()...
Not found '0'
time : 2495663 us.

Flat profile of 26.35 secs (2018 total ticks): main

  Interpreted + native   Method
  0.0%     1  +     0    test.StackOverflow.main
  0.0%     1  +     0    Total interpreted

     Compiled + native   Method
 67.8%  1369  +     0    test.StackOverflow.main
 11.7%   236  +     0    test.StackOverflow.unsafeLookup_8B
 11.2%   227  +     0    test.StackOverflow.unsafeLookup_1B
  9.1%   184  +     0    test.StackOverflow.normalLookup
 99.9%  2016  +     0    Total compiled

         Stub + native   Method
  0.0%     0  +     1    sun.misc.Unsafe.getLong
  0.0%     0  +     1    Total stub


Flat profile of 0.00 secs (1 total ticks): DestroyJavaVM

  Thread-local ticks:
100.0%     1             Blocked (of total)


Global summary of 26.39 seconds:
100.0%  2023             Received ticks


C:\Users\wilf>java -version
java version "1.7.0_07"
Java(TM) SE Runtime Environment (build 1.7.0_07-b11)
Java HotSpot(TM) Client VM (build 23.3-b01, mixed mode, sharing)

CPU 为:Intel Core 2 Duo E4600 @ 2.4GHZ 4.00GB(3.25GB 可用) 操作系统:Windows 7 (32)

在带有 Windows 7_64、32 位 java 的 4 核 AMD64 上运行测试:

initialize data...
initialize data done!

use normalLookup()...
Not found '0'
time : 1631142 us.

use unsafeLookup_1B()...
Not found '0'
time : 2365214 us.

use unsafeLookup_8B()...
Not found '0'
time : 1783320 us.

在带有 Windows 7_64、64 位 java 的 4 核 AMD64 上运行测试:

use normalLookup()...
Not found '0'
time : 655146 us.

use unsafeLookup_1B()...
Not found '0'
time : 904783 us.

use unsafeLookup_8B()...
Not found '0'
time : 764427 us.

Flat profile of 6.34 secs (13 total ticks): main

  Interpreted + native   Method
 23.1%     3  +     0    java.io.PrintStream.println
 23.1%     3  +     0    test.StackOverflow.unsafeLookup_8B
 15.4%     2  +     0    test.StackOverflow.main
  7.7%     1  +     0    java.io.DataInputStream.<init>
 69.2%     9  +     0    Total interpreted

     Compiled + native   Method
  7.7%     0  +     1    test.StackOverflow.unsafeLookup_1B
  7.7%     0  +     1    test.StackOverflow.main
  7.7%     0  +     1    test.StackOverflow.normalLookup
  7.7%     0  +     1    test.StackOverflow.unsafeLookup_8B
 30.8%     0  +     4    Total compiled


Flat profile of 0.00 secs (1 total ticks): DestroyJavaVM

  Thread-local ticks:
100.0%     1             Blocked (of total)


Global summary of 6.35 seconds:
100.0%    14             Received ticks
 42.9%     6             Compilation
4

3 回答 3

5

我认为您发布的两个函数基本相同,因为它们只读取 1 个字节,然后将其转换为 int 并进行进一步比较。

每次读取 4-Byte int 或 8-Byte long 更有效。我写了两个函数来做同样的事情:比较两个 byte[] 的内容,看看它们是否相同:

功能一:

public static boolean hadoopEquals(byte[] b1, byte[] b2)
  {
    if(b1 == b2)
    {
      return true;
    }
    if(b1.length != b2.length)
    {
      return false;
    }
    // Bring WritableComparator code local

    for(int i = 0;i < b1.length; ++i)
    {
     int a = (b1[i] & 0xff);
     int b = (b2[i] & 0xff);
     if (a != b) 
     {
       return false;
     }
    }
    return true;
  }

功能二:

public static boolean goodEquals(byte[] b1,byte[] b2)
  {   
    if(b1 == b2)
    {
      return true;
    }
    if(b1.length != b2.length)
    {
      return false;
    }
    int baseOffset = UnSafe.arrayBaseOffset(byte[].class);

    int numLongs = (int)Math.ceil(b1.length / 8.0);

    for(int i = 0;i < numLongs; ++i)
    {
      long currentOffset = baseOffset + (i * 8);
      long l1 = UnSafe.getLong(b1, currentOffset);
      long l2 = UnSafe.getLong(b2, currentOffset);
      if(0L != (l1 ^ l2))
      {
        return false;
      }
    }
    return true;    
  }

我在笔记本电脑上运行了这两个函数(corei7 2630QM,8GB DDR3,64bit win 7,64bit Hotspot JVM),比较两个400MB byte[],结果如下:

功能1:~670ms

功能2:~80ms

2更快。

所以我的建议是每次读取 8 个字节并使用 XOR 运算符(^):

long l1 = UnSafe.getLong(byteArray, offset);  //8 byte
if(0L == l1 ^ 0xFF)  //if the lowest byte == 0?
/* do something */
if(0L == l1 ^ 0xFF00)  //if the 2nd lowest byte == 0?
/* do something */
/* go on... */

==================================================== ===========================

嗨,Wilf,我使用您的代码制作了一个测试类,如下所示,该类比较了 3 个函数在字节数组中查找第一个 0 的速度:

package test;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

/**
 * Test the speed in looking up the 1st 0 in a byte array
 * Set -Xms the same as -Xms to avoid Heap reallocation
 * 
 * @author yellowb
 *
 */
public class StackOverflow
{
    public static Unsafe UnSafe;

    public static Unsafe getUnsafe() throws SecurityException,
            NoSuchFieldException, IllegalArgumentException,
            IllegalAccessException
    {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        return unsafe;
    }

    /**
     * use 'byte[index]' form to read 1 byte every time
     * @param buf
     */
    public static void normalLookup(byte[] buf)
    {
        for (int i = 0; i < buf.length; ++i)
        {
            if ((byte) 0 == buf[i])
            {
                System.out.println("The 1st '0' is at position : " + i);
                return;
            }
        }
        System.out.println("Not found '0'");
    }

    /**
     * use Unsafe.getByte to read 1 byte every time directly from the memory
     * @param buf
     */
    public static void unsafeLookup_1B(byte[] buf)
    {
        int baseOffset = UnSafe.arrayBaseOffset(byte[].class);
        for (int i = 0; i < buf.length; ++i)
        {
            byte b = UnSafe.getByte(buf, (long) (baseOffset + i));
            if (0 == ((int) b & 0xFF))
            {
                System.out.println("The 1st '0' is at position : " + i);
                return;
            }

        }
        System.out.println("Not found '0'");
    }

    /**
     * use Unsafe.getLong to read 8 byte every time directly from the memory
     * @param buf
     */
    public static void unsafeLookup_8B(byte[] buf)
    {
        int baseOffset = UnSafe.arrayBaseOffset(byte[].class);

        //The first (numLongs * 8) bytes will be read by Unsafe.getLong in below loop
        int numLongs = buf.length / 8;
        long currentOffset = 0L;
        for (int i = 0; i < numLongs; ++i)
        {
            currentOffset = baseOffset + (i * 8);  //the step is 8 bytes
            long l = UnSafe.getLong(buf, currentOffset);
            //Compare each byte(in the 8-Byte long) to 0
            //PS:x86 cpu is little-endian mode
            if (0L == (l & 0xFF))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8));
                return;
            }
            if (0L == (l & 0xFF00L))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8 + 1));
                return;
            }
            if (0L == (l & 0xFF0000L))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8 + 2));
                return;
            }
            if (0L == (l & 0xFF000000L))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8 + 3));
                return;
            }
            if (0L == (l & 0xFF00000000L))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8 + 4));
                return;
            }
            if (0L == (l & 0xFF0000000000L))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8 + 5));
                return;
            }
            if (0L == (l & 0xFF000000000000L))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8 + 6));
                return;
            }
            if (0L == (l & 0xFF00000000000000L))
            {
                System.out.println("The 1st '0' is at position : " + (i * 8 + 7));
                return;
            }
        }

        //If some rest bytes exists
        int rest = buf.length % 8;
        if(0 != rest)
        {
            currentOffset = currentOffset + 8;
            //Because the length of rest bytes < 8,we have to read them one by one
            for(; currentOffset < (baseOffset + buf.length); ++currentOffset)
            {
                byte b = UnSafe.getByte(buf, (long)currentOffset);
                if (0 == ((int) b & 0xFF))
                {
                    System.out.println("The 1st '0' is at position : " + (currentOffset - baseOffset));
                    return;
                }
            }
        }
        System.out.println("Not found '0'");
    }

    public static void main(String[] args) throws SecurityException,
            NoSuchFieldException, IllegalArgumentException,
            IllegalAccessException
    {
        UnSafe = getUnsafe();

        int len = 1024 * 1024 * 1024;  //1G
        long startTime = 0L;
        long endTime = 0L;

        System.out.println("initialize data...");
        byte[] byteArray1 = new byte[len];
        for (int i = 0; i < len; ++i)
        {
            byteArray1[i] = (byte) (i % 128 + 1);  //No byte will equal to 0
        }
        //If you want to set one byte to 0,uncomment the below statement
//      byteArray1[2500] = (byte)0;
        System.out.println("initialize data done!");

        System.out.println("use normalLookup()...");
        startTime = System.nanoTime();
        normalLookup(byteArray1);
        endTime = System.nanoTime();
        System.out.println("time : " + ((endTime - startTime) / 1000) + " us.");

        System.out.println("use unsafeLookup_1B()...");
        startTime = System.nanoTime();
        unsafeLookup_1B(byteArray1);
        endTime = System.nanoTime();
        System.out.println("time : " + ((endTime - startTime) / 1000) + " us.");

        System.out.println("use unsafeLookup_8B()...");
        startTime = System.nanoTime();
        unsafeLookup_8B(byteArray1);
        endTime = System.nanoTime();
        System.out.println("time : " + ((endTime - startTime) / 1000) + " us.");
    }
}

输出是:

initialize data...
initialize data done!
use normalLookup()...
Not found '0'
time : 1271781 us.
use unsafeLookup_1B()...
Not found '0'
time : 716898 us.
use unsafeLookup_8B()...
Not found '0'
time : 591689 us.

结果表明,即使每次通过 Unsafe.getByte() 读取 1 个字节也比定期迭代 byte[] 快得多。并且读取 8 字节长是最快的。

于 2012-09-19T04:50:06.157 回答
1

我认为 Unsafe 可以比使用常规数组访问更快地访问内存,并为每个索引执行索引检查......

范围检查可能不是一个因素的一个可能原因是 JIT 编译器的优化器。由于数组的大小永远不会改变,优化器可能会“提升”所有范围检查并在循环开始时执行一次。

相比之下,JIT 编译器可能无法优化(例如内联) Unsafe.getByte() 调用。或者该getByte方法可能有一个读取障碍......)

然而,这是猜测。确定的方法是让 JVM 为这两种情况转储 JIT 编译的本机代码,并逐条比较它们。

于 2012-09-21T02:01:37.413 回答
0

不安全的方法可能被标记为原生,但这并不意味着它们一定是 JNI。对于_ _ Sun JVM 它们将被转换为单个汇编指令(在许多情况下),对于其他 JVM,它们可能不擅长处理内在函数,并且可能将它们转换为 JNI 调用或纯 java 调用。据我所知,JRockit 倾向于采用 JNI 方式,Android JVM 也是如此。

于 2012-12-25T13:39:17.057 回答