1. public class StringPerformance {
  2. public static void main(String[] args) {
  3. String str1 = "This is a short string.";
  4. String str2 = "This is a much longer string for testing purposes.";
  5. String str3 = "A very very very long string to measure performance.";
  6. long startTime, endTime, duration;
  7. // Measure performance of str1
  8. startTime = System.nanoTime();
  9. processString(str1);
  10. endTime = System.nanoTime();
  11. duration = (endTime - startTime);
  12. System.out.println("String 1 performance: " + duration + " nanoseconds");
  13. // Measure performance of str2
  14. startTime = System.nanoTime();
  15. processString(str2);
  16. endTime = System.nanoTime();
  17. duration = (endTime - startTime);
  18. System.out.println("String 2 performance: " + duration + " nanoseconds");
  19. // Measure performance of str3
  20. startTime = System.nanoTime();
  21. processString(str3);
  22. endTime = System.nanoTime();
  23. duration = (endTime - startTime);
  24. System.out.println("String 3 performance: " + duration + " nanoseconds");
  25. }
  26. // Simulate a short-lived, synchronous task with string processing
  27. public static void processString(String str) {
  28. // Simulate some work being done on the string
  29. for (int i = 0; i < 100000; i++) {
  30. str.toUpperCase(); // Example synchronous operation - converting to uppercase
  31. }
  32. }
  33. }

Add your comment