0

0

“javalangString”内部:理解和优化实例化性能

DDD

DDD

发布时间:2024-12-09 08:12:31

|

584人浏览过

|

来源于dev.to

转载

“javalangstring”内部:理解和优化实例化性能

java.lang.string 可能是 java 中最常用的类之一。当然,它内部包含其字符串数据。但是,您知道这些数据实际上是如何存储的吗?在这篇文章中,我们将探讨 java.lang.string 的内部结构并讨论提高实例化性能的方法。

java 8 或更早版本中 java.lang.string 的内部结构

在 java 8 中,java.lang.string 将其字符串数据包含为 16 位字符数组。

public final class string
    implements java.io.serializable, comparable, charsequence {
    /** the value is used for character storage. */
    private final char value[];

从字节数组实例化 string 时,最终会调用 stringcoding.decode()。

    public string(byte bytes[], int offset, int length, charset charset) {
        if (charset == null)
            throw new nullpointerexception("charset");
        checkbounds(bytes, offset, length);
        this.value =  stringcoding.decode(charset, bytes, offset, length);
    }

对于us_ascii,最终会调用sun.nio.cs.us_ascii.decoder.decode(),将源字节数组的字节一一复制到char数组中。

        public int decode(byte[] src, int sp, int len, char[] dst) {
            int dp = 0;
            len = math.min(len, dst.length);
            while (dp < len) {
                byte b = src[sp++];
                if (b >= 0)
                    dst[dp++] = (char)b;
                else
                    dst[dp++] = repl;
            }
            return dp;
        }

新创建的 char 数组用作新 string 实例的 char 数组值。

正如您所注意到的,即使源字节数组仅包含单字节字符,也会发生字节到字符的复制迭代。

java 9或更高版本中java.lang.string的内部结构

在 java 9 或更高版本中,java.lang.string 将其字符串数据包含为 8 位字节数组。

public final class string
    implements java.io.serializable, comparable, charsequence {

    /**
     * the value is used for character storage.
     *
     * @implnote this field is trusted by the vm, and is a subject to
     * constant folding if string instance is constant. overwriting this
     * field after construction will cause problems.
     *
     * additionally, it is marked with {@link stable} to trust the contents
     * of the array. no other facility in jdk provides this functionality (yet).
     * {@link stable} is safe here, because value is never null.
     */
    @stable
    private final byte[] value;

从字节数组实例化 string 时,还会调用 stringcoding.decode()。

    public string(byte bytes[], int offset, int length, charset charset) {
        if (charset == null)
            throw new nullpointerexception("charset");
        checkboundsoffcount(offset, length, bytes.length);
        stringcoding.result ret =
            stringcoding.decode(charset, bytes, offset, length);
        this.value = ret.value;
        this.coder = ret.coder;
    }

对于 us_ascii,调用 stringcoding.decodeascii(),它使用 arrays.copyofrange() 复制源字节数组,因为源和目标都是字节数组。 arrays.copyofrange() 内部使用 system.arraycopy(),这是一个本机方法并且速度非常快。

    private static result decodeascii(byte[] ba, int off, int len) {
        result result = resultcached.get();
        if (compact_strings && !hasnegatives(ba, off, len)) {
            return result.with(arrays.copyofrange(ba, off, off + len),
                               latin1);
        }
        byte[] dst = new byte[len<<1];
        int dp = 0;
        while (dp < len) {
            int b = ba[off++];
            putchar(dst, dp++, (b >= 0) ? (char)b : repl);
        }
        return result.with(dst, utf16);
    }

您可能会注意到 compact_strings 常量。 java 9 中引入的这一改进称为紧凑字符串。该功能默认启用,但您可以根据需要禁用它。详情请参阅https://docs.oracle.com/en/java/javase/17/vm/java-hotspot-virtual-machine-performance-enhancements.html#guid-d2e3dc58-d18b-4a6c-8167-4a1dfb4888e4。

立即学习Java免费学习笔记(深入)”;

java 8、11、17 和 21 中 new string(byte[]) 的性能

我编写了这个简单的 jmh 基准代码来评估 new string(byte[]) 的性能:

@state(scope.benchmark)
@outputtimeunit(timeunit.milliseconds)
@fork(1)
@measurement(time = 3, iterations = 4)
@warmup(iterations = 2)
public class stringinstantiationbenchmark {
  private static final int str_len = 512;
  private static final byte[] single_byte_str_source_bytes;
  private static final byte[] multi_byte_str_source_bytes;
  static {
    {
      stringbuilder sb = new stringbuilder();
      for (int i = 0; i < str_len; i++) {
        sb.append("x");
      }
      single_byte_str_source_bytes = sb.tostring().getbytes(standardcharsets.utf_8);
    }
    {
      stringbuilder sb = new stringbuilder();
      for (int i = 0; i < str_len / 2; i++) {
        sb.append("あ");
      }
      multi_byte_str_source_bytes = sb.tostring().getbytes(standardcharsets.utf_8);
    }
  }

  @benchmark
  public void newstrfromsinglebytestrbytes() {
    new string(single_byte_str_source_bytes, standardcharsets.utf_8);
  }

  @benchmark
  public void newstrfrommultibytestrbytes() {
    new string(multi_byte_str_source_bytes, standardcharsets.utf_8);
  }
}

基准测试结果如下:

  • java 8
benchmark                        mode  cnt     score     error   units
newstrfrommultibytestrbytes     thrpt    4  1672.397 ±  11.338  ops/ms
newstrfromsinglebytestrbytes    thrpt    4  4789.745 ± 553.865  ops/ms
  • java 11
benchmark                        mode  cnt      score      error   units
newstrfrommultibytestrbytes     thrpt    4   1507.754 ±   17.931  ops/ms
newstrfromsinglebytestrbytes    thrpt    4  15117.040 ± 1241240.981  ops/ms
  • java 17
benchmark                        mode  cnt      score     error   units
newstrfrommultibytestrbytes     thrpt    4   1529.215 ± 168.064  ops/ms
newstrfromsinglebytestrbytes    thrpt    4  17753.086 ± 251.676  ops/ms
  • java 21
benchmark                        mode  cnt      score      error   units
newstrfrommultibytestrbytes     thrpt    4   1543.525 ±   69.061  ops/ms
newstrfromsinglebytestrbytes    thrpt    4  17711.972 ± 1178.212  ops/ms

newstrfromsinglebytestrbytes() 的吞吐量从 java 8 到 java 11 得到了极大的提高。这可能是因为 string 类中从 char 数组更改为 byte 数组。

通过零复制进一步提高性能

好的,紧凑字符串是一个很大的性能改进。但是从字节数组实例化 string 的性能没有提高的空间吗? java 9 或更高版本中的 string(byte bytes[], int offset, int length, charset charset) 复制字节数组。即使它使用 system.copyarray() 这是一个原生方法并且速度很快,但也需要一些时间。

当我阅读 apache fury 的源代码时,它是“一个由 jit(即时编译)和零拷贝驱动的极快的多语言序列化框架”,我发现他们的 stringserializer 实现了零拷贝字符串实例化。让我们看看具体的实现。

网亚Net!B2B
网亚Net!B2B

网亚Net!B2B从企业信息化服务的整体解决方案上提供了实用性的电子商务建站部署,企业无需进行复杂的网站开发,直接使用Net!B2B系列,就能轻松构建具有竞争力的行业门户网站,如果您有特殊需要,系统内置的模板体系和接口体系,让网站可以按照自己的个性要求衍生出庞大的门户服务需求,网亚Net!B2B电子商务建站系统可以让您以希望的方式开展网上服务,无论是为您的客户提供信息服务,新闻服务,产品展示与产品

下载

stringserializer的用法如下:

import org.apache.fury.serializer.stringserializer;

...

    byte[] bytes = "hello".getbytes();
    string s = stringserializer.newbytesstringzerocopy(latin1, bytes);

stringserializer.newbytesstringzerocopy()最终实现的是调用非public string构造函数new string(byte[], byte coder),将源字节数组直接设置为string.value,而不需要复制字节。

stringserializer 有以下 2 个常量:

  private static final bifunction bytes_string_zero_copy_ctr =
      getbytesstringzerocopyctr();
  private static final function latin_bytes_string_zero_copy_ctr =
      getlatinbytesstringzerocopyctr();

bytes_string_zero_copy_ctr 被初始化为从 getbytesstringzerocopyctr() 返回的 bifunction:

  private static bifunction getbytesstringzerocopyctr() {
    if (!string_value_field_is_bytes) {
      return null;
    }
    methodhandle handle = getjavastringzerocopyctrhandle();
    if (handle == null) {
      return null;
    }
    // faster than handle.invokeexact(data, byte)
    try {
      methodtype instantiatedmethodtype =
          methodtype.methodtype(handle.type().returntype(), new class[] {byte[].class, byte.class});
      callsite callsite =
          lambdametafactory.metafactory(
              string_look_up,
              "apply",
              methodtype.methodtype(bifunction.class),
              handle.type().generic(),
              handle,
              instantiatedmethodtype);
      return (bifunction) callsite.gettarget().invokeexact();
    } catch (throwable e) {
      return null;
    }
  }

该方法返回一个 bifunction,它接收 byte[] 值、字节编码器作为参数。该函数调用 methodhandle
对于 string 构造函数 new string(byte[] value, byte coder)。我不知道通过 lambdametafactory.metafactory() 调用 methodhandle 的技术,但它看起来比 methodhandle.invokeexact() 更快。

latin_bytes_string_zero_copy_ctr 被初始化为从 getlatinbytesstringzerocopyctr() 返回的函数:

  private static function getlatinbytesstringzerocopyctr() {
    if (!string_value_field_is_bytes) {
      return null;
    }
    if (string_look_up == null) {
      return null;
    }
    try {
      class clazz = class.forname("java.lang.stringcoding");
      methodhandles.lookup caller = string_look_up.in(clazz);
      // jdk17 removed this method.
      methodhandle handle =
          caller.findstatic(
              clazz, "newstringlatin1", methodtype.methodtype(string.class, byte[].class));
      // faster than handle.invokeexact(data, byte)
      return _jdkaccess.makefunction(caller, handle, function.class);
    } catch (throwable e) {
      return null;
    }
  }

该方法返回一个接收 byte[](不需要编码器,因为它仅适用于 latin1)作为参数的函数,如 getbytesstringzerocopyctr()。但是,这个函数调用 methodhandle
改为 stringcoding.newstringlatin1(byte[] src) 。 _jdkaccess.makefunction() 使用 lambdametafactory.metafactory() 以及 getbytesstringzerocopyctr() 包装 methodhandle 的调用。

stringcoding.newstringlatin1() 在 java 17 中被删除。因此,在 java 17 或更高版本中使用 bytes_string_zero_copy_ctr 函数,否则使用 latin_bytes_string_zero_copy_ctr 函数。

stringserializer.newbytesstringzerocopy() 基本上正确调用了存储在常量中的这些函数。

  public static string newbytesstringzerocopy(byte coder, byte[] data) {
    if (coder == latin1) {
      // 700% faster than unsafe put field in java11, only 10% slower than `new string(str)` for
      // string length 230.
      // 50% faster than unsafe put field in java11 for string length 10.
      if (latin_bytes_string_zero_copy_ctr != null) {
        return latin_bytes_string_zero_copy_ctr.apply(data);
      } else {
        // jdk17 removed newstringlatin1
        return bytes_string_zero_copy_ctr.apply(data, latin1_boxed);
      }
    } else if (coder == utf16) {
      // avoid byte box cost.
      return bytes_string_zero_copy_ctr.apply(data, utf16_boxed);
    } else {
      // 700% faster than unsafe put field in java11, only 10% slower than `new string(str)` for
      // string length 230.
      // 50% faster than unsafe put field in java11 for string length 10.
      // `invokeexact` must pass exact params with exact types:
      // `(object) data, coder` will throw wrongmethodtypeexception
      return bytes_string_zero_copy_ctr.apply(data, coder);
    }
  }

要点是:

  • 调用非公共 stringcoding.newstringlatin1() 或 new string(byte[] value, byte coder) 以避免字节数组复制
  • 尽可能减少反射成本。

是时候进行基准测试了。我更新了 jmh 基准代码如下:

  • 构建.gradle.kts
dependencies {
    implementation("org.apache.fury:fury-core:0.9.0")
    ...
  • org/komamitsu/stringinstantiationbench/stringinstantiationbenchmark.java
package org.komamitsu.stringinstantiationbench;

import org.apache.fury.serializer.stringserializer;
import org.openjdk.jmh.annotations.*;

import java.nio.charset.standardcharsets;
import java.util.concurrent.timeunit;

@state(scope.benchmark)
@outputtimeunit(timeunit.milliseconds)
@fork(1)
@measurement(time = 3, iterations = 4)
@warmup(iterations = 2)
public class stringinstantiationbenchmark {
  private static final int str_len = 512;
  private static final byte[] single_byte_str_source_bytes;
  private static final byte[] multi_byte_str_source_bytes;
  static {
    {
      stringbuilder sb = new stringbuilder();
      for (int i = 0; i < str_len; i++) {
        sb.append("x");
      }
      single_byte_str_source_bytes = sb.tostring().getbytes(standardcharsets.utf_8);
    }
    {
      stringbuilder sb = new stringbuilder();
      for (int i = 0; i < str_len / 2; i++) {
        sb.append("あ");
      }
      multi_byte_str_source_bytes = sb.tostring().getbytes(standardcharsets.utf_8);
    }
  }

  @benchmark
  public void newstrfromsinglebytestrbytes() {
    new string(single_byte_str_source_bytes, standardcharsets.utf_8);
  }

  @benchmark
  public void newstrfrommultibytestrbytes() {
    new string(multi_byte_str_source_bytes, standardcharsets.utf_8);
  }

  // copied from org.apache.fury.serializer.stringserializer.
  private static final byte latin1 = 0;
  private static final byte latin1_boxed = latin1;
  private static final byte utf16 = 1;
  private static final byte utf16_boxed = utf16;
  private static final byte utf8 = 2;

  @benchmark
  public void newstrfromsinglebytestrbyteswithzerocopy() {
    stringserializer.newbytesstringzerocopy(latin1, single_byte_str_source_bytes);
  }

  @benchmark
  public void newstrfrommultibytestrbyteswithzerocopy() {
    stringserializer.newbytesstringzerocopy(utf8, multi_byte_str_source_bytes);
  }
}

结果如下:

  • java 11
benchmark                                  mode  cnt        score      error   units
newstrfrommultibytestrbytes               thrpt    4     1505.580 ±   13.191  ops/ms
newstrfrommultibytestrbyteswithzerocopy   thrpt    4  2284141.488 ± 5509.077  ops/ms
newstrfromsinglebytestrbytes              thrpt    4    15246.342 ±  258.381  ops/ms
newstrfromsinglebytestrbyteswithzerocopy  thrpt    4  2281817.367 ± 8054.568  ops/ms
  • java 17
benchmark                                  mode  cnt        score       error   units
newstrfrommultibytestrbytes               thrpt    4     1545.503 ±    15.283  ops/ms
newstrfrommultibytestrbyteswithzerocopy   thrpt    4  2273566.173 ± 10212.794  ops/ms
newstrfromsinglebytestrbytes              thrpt    4    17598.209 ±   253.282  ops/ms
newstrfromsinglebytestrbyteswithzerocopy  thrpt    4  2277213.103 ± 13380.823  ops/ms
  • java 21
benchmark                                  mode  cnt        score        error   units
newstrfrommultibytestrbytes               thrpt    4     1556.272 ±     16.482  ops/ms
newstrfrommultibytestrbyteswithzerocopy   thrpt    4  3698101.264 ± 429945.546  ops/ms
newstrfromsinglebytestrbytes              thrpt    4    17803.149 ±    204.987  ops/ms
newstrfromsinglebytestrbyteswithzerocopy  thrpt    4  3817357.204 ±  89376.224  ops/ms

由于 npe,java 8 的基准测试代码失败。可能是我用的方法不对。

stringserializer.newbytesstringzerocopy() 的性能在 java 17 中比普通 new string(byte[] bytes, charset charset) 快 100 多倍,在 java 21 中快 200 多倍。也许这就是 fury 速度如此之快的秘密之一。

使用这种零复制策略和实现的一个可能的问题是传递给 new string(byte[] value, byte coder) 的字节数组可能由多个对象拥有;新的 string 对象和引用字节数组的对象。

    byte[] bytes = "Hello".getBytes();
    String s = StringSerializer.newBytesStringZeroCopy(LATIN1, bytes);
    System.out.println(s);    // >>> Hello
    bytes[4] = '!';
    System.out.println(s);    // >>> Hell!

这种可变性可能会导致字符串内容意外更改的问题。

结论

  • 如果您使用 java 8,就 string 实例化的性能而言,请尽可能使用 java 9 或更高版本。
  • 有一种技术可以通过零拷贝从字节数组实例化字符串。速度快得惊人。

相关文章

数码产品性能查询
数码产品性能查询

该软件包括了市面上所有手机CPU,手机跑分情况,电脑CPU,电脑产品信息等等,方便需要大家查阅数码产品最新情况,了解产品特性,能够进行对比选择最具性价比的商品。

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
java
java

Java是一个通用术语,用于表示Java软件及其组件,包括“Java运行时环境 (JRE)”、“Java虚拟机 (JVM)”以及“插件”。php中文网还为大家带了Java相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

835

2023.06.15

java正则表达式语法
java正则表达式语法

java正则表达式语法是一种模式匹配工具,它非常有用,可以在处理文本和字符串时快速地查找、替换、验证和提取特定的模式和数据。本专题提供java正则表达式语法的相关文章、下载和专题,供大家免费下载体验。

741

2023.07.05

java自学难吗
java自学难吗

Java自学并不难。Java语言相对于其他一些编程语言而言,有着较为简洁和易读的语法,本专题为大家提供java自学难吗相关的文章,大家可以免费体验。

736

2023.07.31

java配置jdk环境变量
java配置jdk环境变量

Java是一种广泛使用的高级编程语言,用于开发各种类型的应用程序。为了能够在计算机上正确运行和编译Java代码,需要正确配置Java Development Kit(JDK)环境变量。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

397

2023.08.01

java保留两位小数
java保留两位小数

Java是一种广泛应用于编程领域的高级编程语言。在Java中,保留两位小数是指在进行数值计算或输出时,限制小数部分只有两位有效数字,并将多余的位数进行四舍五入或截取。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

399

2023.08.02

java基本数据类型
java基本数据类型

java基本数据类型有:1、byte;2、short;3、int;4、long;5、float;6、double;7、char;8、boolean。本专题为大家提供java基本数据类型的相关的文章、下载、课程内容,供大家免费下载体验。

446

2023.08.02

java有什么用
java有什么用

java可以开发应用程序、移动应用、Web应用、企业级应用、嵌入式系统等方面。本专题为大家提供java有什么用的相关的文章、下载、课程内容,供大家免费下载体验。

430

2023.08.02

java在线网站
java在线网站

Java在线网站是指提供Java编程学习、实践和交流平台的网络服务。近年来,随着Java语言在软件开发领域的广泛应用,越来越多的人对Java编程感兴趣,并希望能够通过在线网站来学习和提高自己的Java编程技能。php中文网给大家带来了相关的视频、教程以及文章,欢迎大家前来学习阅读和下载。

16926

2023.08.03

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

43

2026.01.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
SQL 教程
SQL 教程

共61课时 | 3.5万人学习

Java 教程
Java 教程

共578课时 | 47.4万人学习

oracle知识库
oracle知识库

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号