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<string>, 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<string>, 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() 这是一个原生方法并且速度很快,但也需要一些时间。

网亚Net!B2B
网亚Net!B2B

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

下载

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

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<byte[], byte, string> bytes_string_zero_copy_ctr =
      getbytesstringzerocopyctr();
  private static final function<byte[], string> latin_bytes_string_zero_copy_ctr =
      getlatinbytesstringzerocopyctr();

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

  private static bifunction<byte[], byte, string> 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<byte[], string> 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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

1010

2023.08.02

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1566

2023.10.24

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

760

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

221

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1566

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

649

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

1228

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

1184

2024.04.29

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

3

2026.03.11

热门下载

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

精品课程

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

共61课时 | 4.3万人学习

Java 教程
Java 教程

共578课时 | 80.7万人学习

oracle知识库
oracle知识库

共0课时 | 0.6万人学习

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

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